minetest-telegram-bridge/bot/bot.py

93 lines
2.8 KiB
Python

#!/usr/bin/env python3
import config
import logging
import requests
import re
from telegram.ext import Updater, MessageHandler, Filters
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - \
%(message)s', level=logging.INFO)
def get_text_or_type(msg, bot, truncate=False):
message = ""
# Set message contents
if msg.text:
if msg.from_user.username == bot.username:
x = re.compile('(<.*?>)(.*)')
y = x.search(msg.text)
z = y.group(2)
message += (z if len(z) <= 10 or not truncate else z[0:9] + "...")
else:
message += (msg.text if len(msg.text) <= 10 or not truncate else
msg.text[0:9] + "...")
elif msg.audio:
message += "[Audio]"
elif msg.document:
message += "[Document]"
elif msg.animation:
message += "[GIF]"
elif msg.game:
message += "[Game]"
elif msg.photo:
message += "[Photo]"
elif msg.sticker:
message += "[Sticker]"
elif msg.video:
message += "[Video]"
elif msg.voice:
message += "[Voice Note]"
elif msg.video_note:
message += "[Video Note]"
elif msg.contact:
message += "[Contact]"
elif msg.location:
message += "[Location]"
elif msg.venue:
message += "[Venue]"
else:
message += "[Unknown type]"
# If caption exists
if msg.caption:
message += (msg.caption if len(msg.caption) <= 10 or not truncate else
msg.caption[0:9] + "...")
# Set sender
return_message = ""
for i in message.strip().split("\n"):
if msg.from_user.username != bot.username:
if msg.from_user.username:
return_message += f"@{msg.from_user.username}: "
else:
return_message += f"{msg.from_user.first_name}: "
else:
x = re.compile('(<.*?>)(.*)')
y = x.search(msg.text)
return_message = y.group(1) + ": " + i + "\n"
# Set the replied to message's contents
if msg.reply_to_message:
return_message += ("[Reply to " +
get_text_or_type(msg.reply_to_message, bot,
True).split("\n")[0] +
f"] ")
return_message += i + "\n"
return return_message.strip()
def message_handling(bot, update):
if update.message.chat.id in config.groups:
message = get_text_or_type(update.message, bot)
params = {"message": message}
requests.post("http://localhost:" + str(config.port) + "/post",
data=params)
updater = Updater(token=config.api_key)
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.all, message_handling))
updater.start_polling()