Files
web2.0-backend/webapp/telegram_bot.py
T
2017-10-16 10:54:02 +03:00

44 lines
1.4 KiB
Python

import sys
import asyncio
import logging
import telepot
from django.conf import settings
from webapp.models import TelegramChannel
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']
if text == '/start':
TelegramChannel.objects.create(channel_id=id)
bot.sendMessage(id, 'Moro! Uudet kaehmyt postataan tälle kanavalle.')
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()
bot.sendMessage(id, 'Lopetetaan kaehmyjen postailu.')
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()
bot.message_loop(kaehmy_handler.handle)
logging.debug('Telepot listening...')