Compare commits

...

5 Commits

3 changed files with 53 additions and 47 deletions

0
data/.gitkeep Normal file
View File

View File

@@ -1,34 +1,13 @@
aiohttp==3.7.3 aiohttp==3.6.3
appdirs==1.4.3
async-timeout==3.0.1 async-timeout==3.0.1
attrs==20.3.0 attrs==20.3.0
CacheControl==0.12.6
certifi==2019.11.28
chardet==3.0.4 chardet==3.0.4
colorama==0.4.3 idna==3.1
contextlib2==0.6.0 idna-ssl==1.1.0
decorator==4.4.2 multidict==4.7.6
distlib==0.3.0
distro==1.4.0
html5lib==1.0.1
idna==2.8
ipaddr==2.2.0
lockfile==0.12.2
msgpack==0.6.2
multidict==5.1.0
packaging==20.3
pep517==0.8.2
progress==1.5
pyaes==1.6.1 pyaes==1.6.1
pyasn1==0.4.8 pyasn1==0.4.8
pyparsing==2.4.6 rsa==4.7.2
pytoml==0.1.21 Telethon==1.21.1
requests==2.22.0
retrying==1.3.3
rsa==4.7.1
six==1.14.0
Telethon==1.19.5
typing-extensions==3.7.4.3 typing-extensions==3.7.4.3
urllib3==1.25.8 yarl==1.5.1
webencodings==0.5.1
yarl==1.6.3

View File

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