darkirc: rewrite telegram mirror bot to exit gracfully

This commit is contained in:
dasman
2025-02-01 04:19:59 +03:00
parent 54b891c905
commit 6a4bf914ac

View File

@@ -1,48 +1,26 @@
import asyncio, json, traceback
import asyncio
import traceback
import html.parser
import telegram
from telegram import Bot, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
import irc
import signal
from telegram import Bot
from io import StringIO
TOKEN = "..."
TOKEN_TEST = "..."
SERVER = "127.0.0.1"
PORT = 6645
CHANNELS = ["#dev","#memes","#philosophy","#markets","#math","#random",]
BOTNICK = "tgbridge"
class IrcBot:
async def connect(self, server, port):
self._reader, self._writer = await asyncio.open_connection(server, port)
self._send("USER tgbridge 0 * :tgbridge")
self._send("NICK tgbridge")
await self._recv()
self._send("CAP REQ :no-history")
await self._recv()
self._send("CAP END")
def signal_handler(sig, frame):
print("Caught termination signal, cleaning up and exiting...")
ircc.disconnect(SERVER, PORT)
print("Shut down successfully")
exit(0)
def _send(self, msg):
msg += "\r\n"
self._writer.write(msg.encode())
async def _recv(self):
message = await self._reader.readline()
message = message.decode()
return message.removesuffix("\r\n")
async def get_message(self):
while True:
line = await self._recv()
print(f"Received line: {line}")
tokens = line.split(" ")
if len(tokens) < 2 or tokens[1] != "PRIVMSG":
continue
assert tokens[0][0] == ":"
username = tokens[0].split("!")[0][1:]
channel = tokens[2]
message = ":".join(line.split(":")[2:])
return (username, channel, message)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
class HTMLTextExtractor(html.parser.HTMLParser):
def __init__(self):
@@ -69,51 +47,63 @@ def append_log(channel, username, message):
with open(f"/srv/http/log/all.txt", "a") as fd:
fd.write(f"{channel} <{username}> {message}\n")
ircc = irc.IRC()
ircc.connect(SERVER, PORT, CHANNELS, BOTNICK)
async def main():
irc = IrcBot()
await irc.connect("localhost", 6667)
while True:
nick, channel, message = await irc.get_message()
if message.lower() == "test":
continue
if nick == "testbot":
text = ircc.get_response()
# print(text)
if not len(text) > 0:
continue
text_list = text.split(' ')
nick = text_list[0].split('!')[0][1:]
if text_list[1] == "PRIVMSG":
channel = text_list[2]
message = ' '.join(text_list[3:])
# remove the prefix
message = message[1:]
# ignore test msgs
if message.lower() == "test" or message.lower() == "echo":
continue
if nick == "testbot":
continue
# Strip all HTML tags
#message = html_to_text(message)
message = message.replace("<", "&lt;")
message = message.replace(">", "&gt;")
# Limit line lengths
message = message[:300]
# Strip all HTML tags
#message = html_to_text(message)
message = message.replace("<", "&lt;")
message = message.replace(">", "&gt;")
# Limit line lengths
message = message[:300]
# Left pad nickname
nick = nick.replace("<", "&lt;")
nick = nick.replace(">", "&gt;")
nick = nick.rjust(12)
# Left pad nickname
nick = nick.replace("<", "&lt;")
nick = nick.replace(">", "&gt;")
nick = nick.rjust(12)
# Limit line lengths
message = message[:300]
msg = f"<code>{channel} {nick} |</code> {message}"
# Limit line lengths
message = message[:300]
msg = f"<code>{channel} {nick} |</code> {message}"
append_log(channel, nick, message)
# print(msg)
# Keep retrying until the fucker is sent
while True:
try:
async with Bot(TOKEN) as bot:
await bot.send_message("@darkfi_darkirc", msg,
parse_mode="HTML",
disable_notification=True,
disable_web_page_preview=True)
break
#except telegram.error.BadRequest:
# pass
except:
print(channel, msg)
print(traceback.format_exc())
await asyncio.sleep(3)
append_log(channel, nick, message)
# Keep retrying until the fucker is sent
while True:
try:
async with Bot(TOKEN) as bot:
await bot.send_message("@darkfi_darkirc", msg,
parse_mode="HTML",
disable_notification=True,
disable_web_page_preview=True)
break
#except telegram.error.BadRequest:
# pass
except:
print(channel, msg)
print(traceback.format_exc())
await asyncio.sleep(3)
asyncio.run(main())