From cc30868574a6ed31101a6b6753b2da8edf3a97c7 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 5 Mar 2017 19:12:02 +0100 Subject: [PATCH] Added telegram<->discord bridge --- basicbot.py | 47 +++++++++++++++++++++++++++++++++++++++++++++-- telegram.py | 13 +++++++++++-- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/basicbot.py b/basicbot.py index cf45b735..747b80b2 100644 --- a/basicbot.py +++ b/basicbot.py @@ -1,11 +1,15 @@ import asyncio +import json + loop = asyncio.get_event_loop() import telegram import random import datetime +import async_timeout +import aiohttp +import royalbotconfig - -b = telegram.Bot("lul") +b = telegram.Bot(royalbotconfig.telegram_token) async def diario(bot, update, arguments): @@ -68,7 +72,46 @@ Sintassi: `/help [comando]`""" await update.message.chat.send_message(bot, "⚠ Il comando specificato non esiste.") +async def discord(bot, update, arguments): + """Manda un messaggio a #chat di Discord. + +Sintassi: `/discord `""" + # 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 `") + return + username = f"{update.message.sent_from}" + 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.chat.send_message(bot, "⚠ L'invio del messaggio è fallito. Oops!") + # TODO: handle Discord webhooks errors + raise Exception("Qualcosa è andato storto durante l'invio del messaggio a Discord.") + # Answer on Telegram + await update.message.chat.send_message(bot, "Richiesta inviata.") + + b.commands["leggi"] = leggi b.commands["diario"] = diario +b.commands["discord"] = discord b.commands["help"] = help b.run() \ No newline at end of file diff --git a/telegram.py b/telegram.py index 75aa8421..d68c0c11 100644 --- a/telegram.py +++ b/telegram.py @@ -130,13 +130,13 @@ class Bot: async def api_request(self, endpoint, t=10, **params): """Send a request to the Telegram API at the specified endpoint.""" # Request timeout is 10 seconds. + # TODO: get rid of that t variable with async_timeout.timeout(t): # Create a new session for each request. async with aiohttp.ClientSession() as session: # Send the request to the Telegram API token = self.token - async with session.request("GET", f"https://api.telegram.org/bot{token}/{endpoint}", - params=params) as response: + async with session.request("GET", f"https://api.telegram.org/bot{token}/{endpoint}", params=params) as response: # Check for errors in the request if response.status != 200: raise TelegramAPIError(f"Request returned {response.status} {response.reason}") @@ -237,6 +237,15 @@ class User: else: self.username = None + def __str__(self): + if self.username is not None: + return f"@{self.username}" + else: + if self.last_name is not None: + return f"{self.first_name} {self.last_name}" + else: + return self.first_name + def __repr__(self): if self.username is not None: return f""