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

280 lines
11 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
import markovify
2017-03-14 13:34:20 +00:00
import discord
2017-03-05 17:14:45 +00:00
2017-03-05 18:12:02 +00:00
b = telegram.Bot(royalbotconfig.telegram_token)
d = discord.Client()
2017-02-27 22:16:42 +00:00
2017-03-10 10:52:20 +00:00
def currently_logged_in(update):
2017-03-10 14:52:26 +00:00
"""Trova l'utente connesso all'account di Telegram che ha mandato l'update."""
2017-03-10 10:52:20 +00:00
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:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Non sei autorizzato a eseguire questo comando.", parse_mode="Markdown")
2017-03-10 11:00:37 +00:00
return
2017-03-05 17:14:45 +00:00
if len(arguments) == 0:
2017-03-13 14:32:51 +00:00
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/diario <random | markov | numerofrase>`", parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
return
entry = " ".join(arguments)
if not entry.isprintable():
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ La frase che stai provando ad aggiungere contiene caratteri non ASCII, quindi non è stata aggiunta.\nToglili e riprova!", parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
return
entry = entry.replace("\n", " ")
time = update.message.date.timestamp()
file = open("diario.txt", "a", encoding="utf8")
2017-03-05 17:14:45 +00:00
file.write(f"{int(time)}|{entry}\n")
file.close()
del file
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "Aggiunto al diario!", parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
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>`.
2017-03-13 18:13:42 +00:00
Sintassi: `/leggi <random | numerofrase>`"""
2017-03-05 17:14:45 +00:00
if len(arguments) == 0 or len(arguments) > 1:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/leggi <random | numerofrase>`", parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
return
2017-03-13 18:13:42 +00:00
file = open("diario.txt", "r")
entries = file.read().split("\n")
2017-03-05 17:14:45 +00:00
file.close()
2017-03-13 18:13:42 +00:00
if arguments[0] == "random":
entry_number = random.randrange(len(entries))
2017-03-05 17:14:45 +00:00
else:
2017-03-13 18:13:42 +00:00
entry_number = arguments[0]
entry = entries[entry_number].split("|", 1)
date = datetime.datetime.fromtimestamp(entry[0]).isoformat()
2017-03-05 17:14:45 +00:00
text = entry[1]
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, f"Frase #{entry_number} | {date}\n{text}", parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
2017-03-13 18:13:42 +00:00
async def markov(bot, update, arguments):
"""Genera una frase del diario utilizzando le catene di Markov.
Puoi specificare con che parola deve iniziare la frase generata.
Sintassi: `/markov [inizio]`"""
file = open("diario.txt", "r", encoding="utf8")
# Clean the diario
clean_diario = str()
# Remove the timestamps in each row
for row in file:
clean_diario += row.split("|", 1)[1].lower()
2017-03-13 18:13:42 +00:00
# The text is split by newlines
generator = markovify.NewlineText(clean_diario)
file.close()
if len(arguments) == 0:
# Generate a sentence with a random start
2017-03-14 13:02:10 +00:00
text = generator.make_sentence(tries=50)
2017-03-13 18:13:42 +00:00
else:
# Generate a sentence with a specific start
start = " ".join(arguments)
2017-03-14 13:02:10 +00:00
try:
text = generator.make_sentence_with_start(start, tries=100)
# No entry can start in that word.
except KeyError:
await update.message.reply(bot, f"⚠ Non sono state trovate corrispondenze nel diario dell'inizio che hai specificato.", parse_mode="Markdown")
return
if text is not None:
await update.message.reply(bot, f"*Frase generata:*\n{text}", parse_mode="Markdown")
else:
await update.message.reply(bot, f"⚠ Il bot non è riuscito a generare una nuova frase.\nSe è la prima volta che vedi questo errore, riprova, altrimenti prova a cambiare configurazione.")
2017-03-13 18:13:42 +00:00
2017-03-14 13:02:10 +00:00
async def help_cmd(bot, update, arguments):
2017-03-05 17:14:45 +00:00
"""Visualizza la descrizione di un comando.
Sintassi: `/help [comando]`"""
if len(arguments) == 0:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, help.__doc__, parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
elif len(arguments) > 1:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/help [comando]`", parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
else:
if arguments[0] in b.commands:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, b.commands[arguments[0]].__doc__, parse_mode="Markdown")
2017-03-05 17:14:45 +00:00
else:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Il comando specificato non esiste.", parse_mode="Markdown")
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:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/discord <messaggio>`", parse_mode="Markdown")
2017-03-05 18:12:02 +00:00
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
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ L'invio del messaggio è fallito. Oops!", parse_mode="Markdown")
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
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "Richiesta inviata.", parse_mode="Markdown")
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-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/sync <username> <password>`", parse_mode="Markdown")
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-12 17:55:59 +00:00
print(f"{logged_user} ha sincronizzato l'account.")
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, f"Sincronizzazione riuscita!\nSei loggato come `{logged_user}`.", parse_mode="Markdown")
2017-03-10 09:11:06 +00:00
else:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ L'account è già stato sincronizzato.", parse_mode="Markdown")
2017-03-09 14:52:02 +00:00
else:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Username o password non validi.", parse_mode="Markdown")
2017-03-09 14:52:02 +00:00
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:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/changepassword <oldpassword> <newpassword>`", parse_mode="Markdown")
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-13 11:57:04 +00:00
await update.message.reply(bot, f"Il cambio password è riuscito!\n\n_Info per smanettoni: la tua password è hashata nel database come_ `{logged_user.password}`.", parse_mode="Markdown")
2017-03-10 09:34:27 +00:00
else:
2017-03-13 11:57:04 +00:00
await update.message.reply(bot, "⚠ Username o password non validi.", parse_mode="Markdown")
2017-03-10 09:34:27 +00:00
async def cv(bot, update, arguments):
"""Visualizza lo stato attuale della chat vocale Discord.
Sintassi: `/cv`"""
if len(arguments) != 0:
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/cv`", parse_mode="Markdown")
return
# Wait for the Discord bot to login
while not d.is_logged_in:
await asyncio.sleep(1)
# Find all the users in the server
# Change this if the bot is logged in more than one server at once?
users = list(d.get_all_members())
# Find all the channels
channels = dict()
for user in users:
if user.voice_channel is not None:
if user.voice_channel.name not in channels:
channels[user.voice_channel.name] = list()
channels[user.voice_channel.name].append(user)
# Create the string to send to Telegram
to_send = str()
for channel in channels:
# Channel header
to_send += f"*{channel}:*\n"
# Users in channel
for user in channels[channel]:
# Online status
if user.status.name == "online":
status = "🔵"
elif user.status.name == "dnd":
status = ""
elif user.status.name == "idle":
status = ""
elif user.status.name == "offline":
status = ""
else:
status = ""
# Voice status
if user.bot:
volume = "🎵"
elif user.voice.deaf or user.voice.self_deaf:
volume = "🔇"
elif user.voice.mute or user.voice.self_mute:
volume = "🔈"
else:
volume = "🔊"
# Game, is formatted
if user.game is not None:
game = f"- *{user.game.name}*"
else:
game = ""
# Name
if user.nick is not None:
name = user.nick
else:
name = user.name
# Add the user
to_send += f"{volume} {status} {name} {game}\n"
# Channel footer
to_send += "\n"
await update.message.reply(bot, to_send, parse_mode="Markdown")
if __name__ == "__main__":
# Init Telegram bot commands
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
2017-03-14 13:02:10 +00:00
b.commands["help"] = help_cmd
2017-03-13 18:13:42 +00:00
b.commands["markov"] = markov
b.commands["cv"] = cv
# Init Telegram bot
loop.create_task(b.run())
print("Telegram bot start scheduled!")
# Init Discord bot
loop.run_until_complete(d.login(royalbotconfig.discord_token))
loop.create_task(d.connect())
print("Discord bot start scheduled!")
# Run everything!
loop.run_forever()