2021-03-02 00:29:21 +00:00
|
|
|
import aiohttp
|
|
|
|
import asyncio
|
2021-03-02 10:32:27 +00:00
|
|
|
import emoji
|
2021-03-02 00:29:21 +00:00
|
|
|
import logging
|
|
|
|
import re
|
|
|
|
import settings
|
|
|
|
from telethon import TelegramClient, events
|
|
|
|
|
|
|
|
bot = TelegramClient('bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
|
|
|
|
web = None
|
|
|
|
api = lambda route: settings.DYNMAP_ADDRESS + route
|
2021-03-02 10:32:27 +00:00
|
|
|
emojis = list(emoji.unicode_codes.UNICODE_EMOJI_ENGLISH.keys())
|
2021-03-02 00:29:21 +00:00
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
|
|
@bot.on(events.NewMessage(incoming=True))
|
|
|
|
async def new_message(event):
|
|
|
|
text = event.raw_text
|
|
|
|
sender = await event.get_sender()
|
|
|
|
|
|
|
|
if event.chat.id != settings.CHAT_ID:
|
|
|
|
logging.info('Wrong chat ID')
|
|
|
|
return
|
|
|
|
|
|
|
|
if not text:
|
|
|
|
logging.info('No text found')
|
|
|
|
return
|
|
|
|
|
|
|
|
name = re.sub(r'\W+', '', sender.first_name) + '(TG)'
|
|
|
|
|
|
|
|
logging.info('[SEND] {}: {}'.format(name, text))
|
|
|
|
|
|
|
|
data = dict(name=name, message=text)
|
|
|
|
await web.post(api('/up/sendmessage'), json=data)
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
global web
|
|
|
|
web = aiohttp.ClientSession()
|
|
|
|
last_time = 0
|
|
|
|
last_msg = ''
|
|
|
|
|
|
|
|
while True:
|
|
|
|
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'].endswith('(TG)'): continue
|
2021-03-02 10:32:27 +00:00
|
|
|
|
|
|
|
name = update['playerName']
|
|
|
|
icon = emojis[hash(name) % len(emojis)]
|
|
|
|
message = '{} <{}> {}'.format(icon, name, update['message'])
|
2021-03-02 00:29:21 +00:00
|
|
|
if message == last_msg: continue
|
|
|
|
|
|
|
|
logging.info('[RECV] ' + message)
|
|
|
|
await bot.send_message(settings.CHAT_ID, message)
|
|
|
|
last_msg = message
|
|
|
|
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
|
|
with bot:
|
|
|
|
bot.loop.run_until_complete(main())
|