Files
web2.0-backend/webapp/telegram_bot.py
T
2017-10-16 14:42:06 +03:00

67 lines
2.2 KiB
Python

import sys
import asyncio
import logging
import telepot
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete, pre_save
from webapp.models import TelegramChannel, TelegramMessage
TOKEN = settings.TELEGRAM_BOT_TOKEN
bot = telepot.Bot(TOKEN)
logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
logging.getLogger('urllib3.util.retry').setLevel(logging.WARNING)
class KaehmyHandler:
def handle(self, msg):
flavor = telepot.flavor(msg)
if flavor == 'chat':
text = msg['text']
id = msg['chat']['id']
msg_id = msg['message_id']
if text == '/start':
TelegramChannel.objects.create(channel_id=id)
try:
TelegramMessage.objects.create(message_id=msg_id, channel_id=id, text='Moro! Uudet kaehmyt postataan tälle kanavalle.')
except:
pass
elif text == '/stop':
channels_started = [int(channel.channel_id) for channel in TelegramChannel.objects.all()]
if id in channels_started:
TelegramChannel.objects.get(channel_id=id).delete()
try:
TelegramMessage.objects.create(message_id=msg_id, channel_id=id, text='Lopetetaan kaehmyjen postailu.')
except:
pass
def announce(self, url, name):
channels_started = [channel.channel_id for channel in TelegramChannel.objects.all()]
logging.debug('Announcing to {} Telegram channels.'.format(len(channels_started)))
for id in channels_started:
bot.sendMessage(id, 'Uusi kaehmy/New kaehmy! {} -> {}'.format(name, url))
kaehmy_handler = KaehmyHandler()
def main():
bot.message_loop(kaehmy_handler.handle)
logging.debug('Telepot listening...')
try:
bot.getMe()
main()
except Exception as ex:
logging.exception('Failed to create Telegram bot with token "{}"'.format(TOKEN))
@receiver(post_save, sender=TelegramMessage, dispatch_uid="save_tg_message")
def save_message(sender, instance, **kwargs):
bot.sendMessage(instance.channel_id, instance.text)
instance.save()