1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/basicbot.py

171 lines
6.6 KiB
Python
Raw Normal View History

2017-02-27 22:16:42 +00:00
import asyncio
loop = asyncio.get_event_loop()
import telegram
2017-03-05 17:14:45 +00:00
import random
import datetime
2017-03-05 18:12:02 +00:00
import async_timeout
import aiohttp
import royalbotconfig
import json
2017-03-09 14:52:02 +00:00
import database
2017-03-05 17:14:45 +00:00
2017-03-05 18:12:02 +00:00
b = telegram.Bot(royalbotconfig.telegram_token)
2017-02-27 22:16:42 +00:00
2017-03-10 10:52:20 +00:00
def currently_logged_in(update):
"""Find the database user which sent the update."""
session = database.Session()
user = session.query(database.User).filter_by(telegram_id=update.message.sent_from.user_id).first()
2017-03-10 11:00:37 +00:00
return user
2017-03-10 10:52:20 +00:00
async def diario(bot, update, arguments):
2017-03-05 17:14:45 +00:00
"""Aggiungi una frase al diario Royal Games.
2017-03-10 11:00:37 +00:00
Devi essere un Royal per poter eseguire questo comando.
2017-03-05 17:14:45 +00:00
Sintassi: `/diario <frase>`"""
2017-03-10 11:00:37 +00:00
if not currently_logged_in(update).royal:
await update.message.chat.send_message(bot, "⚠ Non sei autorizzato a eseguire questo comando.")
return
2017-03-05 17:14:45 +00:00
if len(arguments) == 0:
await update.message.chat.send_message(bot, "⚠ Sintassi del comando non valida.\n`/diario <random | numerofrase>`")
return
entry = " ".join(arguments)
if not entry.isprintable():
await update.message.chat.send_message(bot, "⚠ La frase che stai provando ad aggiungere contiene caratteri non ASCII, quindi non è stata aggiunta.\nToglili e riprova!")
return
entry = entry.replace("\n", " ")
time = update.message.date.timestamp()
file = open("diario.txt", "a")
file.write(f"{int(time)}|{entry}\n")
file.close()
del file
await update.message.chat.send_message(bot, "Aggiunto al diario!")
async def leggi(bot, update, arguments):
"""Leggi una frase dal diario Royal Games.
Puoi visualizzare il diario [qui](https://royal.steffo.me/diario.htm), leggere una frase casuale scrivendo `/leggi random` o leggere una frase specifica scrivendo `/leggi <numero>`.
Sintassi: `/leggi <random | numerofrase>`"""
if len(arguments) == 0 or len(arguments) > 1:
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/leggi <random | numerofrase>`")
2017-03-05 17:14:45 +00:00
return
file = open("diario.txt", "r")
entries = file.read().split("\n")
file.close()
if arguments[0] == "random":
entry_number = random.randrange(len(entries))
else:
entry_number = arguments[0]
entry = entries[entry_number].split("|", 1)
date = datetime.datetime.fromtimestamp(entry[0]).isoformat()
text = entry[1]
await update.message.reply(bot, f"Frase #{entry_number} | {date}\n{text}")
2017-03-05 17:14:45 +00:00
async def help(bot, update, arguments):
"""Visualizza la descrizione di un comando.
Sintassi: `/help [comando]`"""
if len(arguments) == 0:
await update.message.reply(bot, help.__doc__)
2017-03-05 17:14:45 +00:00
elif len(arguments) > 1:
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/help [comando]`")
2017-03-05 17:14:45 +00:00
else:
if arguments[0] in b.commands:
await update.message.reply(bot, b.commands[arguments[0]].__doc__)
2017-03-05 17:14:45 +00:00
else:
await update.message.reply(bot, "⚠ Il comando specificato non esiste.")
2017-03-05 17:14:45 +00:00
2017-02-27 22:16:42 +00:00
2017-03-05 18:12:02 +00:00
async def discord(bot, update, arguments):
"""Manda un messaggio a #chat di Discord.
Sintassi: `/discord <messaggio>`"""
# TODO: create a discord module
# Send a message through a Discord webhook
# Message to send
if len(arguments) == 0:
await update.message.chat.send_message(bot, "⚠ Sintassi del comando non valida.\n`/discord <messaggio>`")
return
username = str(update.message.sent_from)
2017-03-05 18:12:02 +00:00
message = " ".join(arguments)
# Parameters to send
params = {
# TODO: show the message sender's Discord username
"content": f"{username}: {message}"
}
# Headers to send
headers = {
"Content-Type": "application/json"
}
# Request timeout is 10 seconds.
with async_timeout.timeout(10):
# Create a new session for each request.
async with aiohttp.ClientSession() as session:
# Send the request to the Discord webhook
async with session.request("POST", royalbotconfig.discord_webhook, data=json.dumps(params), headers=headers) as response:
# Check if the request was successful
if response.status != 204:
# Request failed
# Answer on Telegram
await update.message.reply(bot, "⚠ L'invio del messaggio è fallito. Oops!")
2017-03-05 18:12:02 +00:00
# TODO: handle Discord webhooks errors
raise Exception("Qualcosa è andato storto durante l'invio del messaggio a Discord.")
# Answer on Telegram
await update.message.reply(bot, "Richiesta inviata.")
2017-03-05 18:12:02 +00:00
2017-03-10 09:11:06 +00:00
async def sync(bot, update, arguments):
"""Connetti il tuo account Telegram al Database Royal Games.
2017-03-09 14:52:02 +00:00
2017-03-10 09:11:06 +00:00
Sintassi: `/sync <username> <password>`"""
2017-03-09 14:52:02 +00:00
if len(arguments) != 2:
2017-03-10 09:11:06 +00:00
await update.message.chat.send_message(bot, "⚠ Sintassi del comando non valida.\n`/sync <username> <password>`")
2017-03-09 14:52:02 +00:00
return
2017-03-10 09:11:06 +00:00
# Try to login
session, logged_user = database.login(arguments[0], arguments[1])
# Check if the login is successful
2017-03-09 14:52:02 +00:00
if logged_user is not None:
2017-03-10 09:11:06 +00:00
# Add the telegram_id to the user if it's missing
if logged_user.telegram_id is None:
# Handle duplicate
logged_user.telegram_id = update.message.sent_from.user_id
session.commit()
2017-03-10 10:52:20 +00:00
await update.message.chat.send_message(bot, f"Sincronizzazione riuscita!\nSei loggato come `{logged_user}`.")
2017-03-10 09:11:06 +00:00
else:
await update.message.chat.send_message(bot, "⚠ L'account è già stato sincronizzato.")
2017-03-09 14:52:02 +00:00
else:
await update.message.chat.send_message(bot, "⚠ Username o password non validi.")
2017-03-10 09:34:27 +00:00
async def changepassword(bot, update, arguments):
"""Cambia la tua password del Database Royal Games.
2017-03-10 10:52:20 +00:00
Sintassi: `/changepassword <newpassword>`"""
if len(arguments) != 2:
await update.message.chat.send_message(bot, "⚠ Sintassi del comando non valida.\n`/changepassword <oldpassword> <newpassword>`")
2017-03-10 09:34:27 +00:00
return
2017-03-10 10:52:20 +00:00
# TODO: this can be improved, maybe?
2017-03-10 11:00:37 +00:00
logged_user = currently_logged_in(update)
2017-03-10 09:34:27 +00:00
# Check if the login is successful
if logged_user is not None:
# Change the password
2017-03-10 10:52:20 +00:00
database.change_password(logged_user.username, arguments[1])
2017-03-10 09:34:27 +00:00
await update.message.chat.send_message(bot, f"Il cambio password è riuscito!\n\n_Info per smanettoni: la tua password è hashata nel database come_ `{logged_user.password}`.")
else:
await update.message.chat.send_message(bot, "⚠ Username o password non validi.")
if __name__ == "__main__":
b.commands["leggi"] = leggi
b.commands["diario"] = diario
b.commands["discord"] = discord
2017-03-10 09:11:06 +00:00
b.commands["sync"] = sync
2017-03-10 09:34:27 +00:00
b.commands["changepassword"] = changepassword
b.commands["help"] = help
b.run()