You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
3.4 KiB

import aiohttp
import asyncio
import hashlib
import logging
import re
import settings
from telethon import TelegramClient, events
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
web = None
api = lambda route: settings.DYNMAP_ADDRESS + route
md5 = lambda name: int(hashlib.md5(name.encode()).hexdigest(), 16)
emojis = list('🌹🏵🌻🌼🍀🏞🌊⛄🏔🌡🔥🏜☀💧☔🌈⭐🌍🌙🪐🐵🦁🐯🐱🐶🐺🐻🐼🐹🐰🦊🦝🦓🦄🐸🐢🐕🐆🐏🦥🐘🦏🦒🦍🐪🦦🐔🐤🦉🦜🦢🦩🐧🐬🐠🐡🦐🐙🕷🐌🐞🦋🍓🍒🍎🍉🍍🍌🍋🍐🥝🍇🥥🍅🌶🍄🥕🧅🌽🥦🥑🍞🥞🧇🧀🥓🍔🌭🥪🥨🍟🍕🌮🥙🍜🍣🍭🍩🍪🍯🍿🍺🍷🛹🚀🛸🛩🎉🎈🎀🎁⚾🏀🏐🏈🎯🎹🎷🎺🎸💵💰💡💎🟥🟧🟨🟩🟦🟪')
logging.basicConfig(level=logging.INFO)
logging.info('Loaded {} emojis'.format(len(emojis)))
3 years ago
logging.info('Bridge initialized')
@bot.on(events.NewMessage(incoming=True))
async def new_message(event):
text = event.raw_text
sender = await event.get_sender()
reply_name = ''
if event.chat.id != settings.CHAT_ID:
logging.info('Wrong chat ID')
return
if not text:
logging.info('No text found')
return
if event.message.is_reply:
reply_msg = await event.get_reply_message()
reply_text = reply_msg.text
reply_name = reply_msg.sender.first_name
if reply_name == 'protospace_mc_bot':
match = re.search(r'<(\w+)>.*', reply_text)
if match:
reply_name, = match.groups()
else:
reply_name = ''
if reply_name:
reply_name = settings.CUSTOM_NAMES.get(reply_name, reply_name)
text = reply_name + ': ' + text
name = re.sub(r'\W+', '', sender.first_name)
name = '[TG] ' + settings.CUSTOM_NAMES.get(name, name)
logging.info('[SEND] {}: {}'.format(name, text))
data = dict(name=name, message=text)
try:
await web.post(api('/up/sendmessage'), json=data)
except aiohttp.ClientError:
logging.exception('Problem sending message to dynmap:')
async def main():
global web
web = aiohttp.ClientSession()
last_time = 0
last_msg = ''
3 years ago
logging.info('Bridge loaded')
while True:
try:
async with web.get(api('/up/world/world/' + str(last_time))) as res:
j = await res.json(content_type='text/plain;charset=utf-8')
last_time = j['timestamp']
for update in j['updates']:
if update['type'] != 'chat': continue
if update['playerName'].startswith('[TG] '): continue
name = update['playerName']
icon = emojis[md5(name) % len(emojis)]
icon = settings.CUSTOM_EMOJIS.get(name, icon)
message = '{} <{}> {}'.format(icon, name, update['message'])
if message == last_msg: continue
logging.info('[RECV] ' + message)
await bot.send_message(settings.CHAT_ID, message)
last_msg = message
except aiohttp.ClientError:
logging.exception('Problem getting message from dynmap:')
await asyncio.sleep(1)
with bot:
bot.loop.run_until_complete(main())