tbr/tbr.py

160 lines
4.9 KiB
Python
Raw Normal View History

2017-06-10 20:02:53 +03:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# msg.py
#
# Copyright 2017 Jyri Eerola <je1@clr-f55255f3d66b4bfba1010f57f9384f00>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import json
2018-04-02 22:00:47 +03:00
import logging
2017-06-10 20:38:52 +03:00
from pprint import pformat
2018-04-02 22:00:47 +03:00
from multiprocessing import Process
2017-06-10 20:02:53 +03:00
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
2018-04-02 22:00:47 +03:00
from telegram.error import (TelegramError, Unauthorized, BadRequest,
TimedOut, ChatMigrated, NetworkError)
2017-06-10 20:02:53 +03:00
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
2018-04-02 22:00:47 +03:00
2017-06-10 20:02:53 +03:00
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
update.message.reply_text('Hullo!')
def halp(bot, update):
update.message.reply_text('Halp!')
def fok(bot, update):
update.message.reply_text('Fok!')
def echo(bot, update):
update.message.reply_text(update.message.text)
2018-04-02 22:00:47 +03:00
def error_callback(bot, update, error):
try:
raise error
except Unauthorized:
# remove update.message.chat_id from conversation list
logger.warning(error.msg)
except BadRequest:
# handle malformed requests - read more below!
logger.warning(error.msg)
except TimedOut:
# handle slow connection problems
logger.warning('TimedOut occurred')
except NetworkError:
# handle other connection problems
logger.warning(error.msg)
except ChatMigrated as e:
# the chat_id of a group has changed, use e.new_chat_id instead
logger.warning(error.msg)
except TelegramError:
# handle all other telegram related errors
logger.warning(error.msg)
2017-06-10 20:02:53 +03:00
routingdict = dict()
def route(bot, update, args):
chat_id = update.message.chat_id
source_id = ' '.join(args)
if source_id not in routingdict:
routingdict[source_id]=set()
routingdict[source_id].add(chat_id)
bot.send_message(chat_id=chat_id, text="New route: {} -> {}".format(source_id, chat_id))
def print_routes(bot, update):
2017-06-10 20:38:52 +03:00
update.message.reply_text(pformat(routingdict))
2017-06-10 20:02:53 +03:00
2018-04-02 22:00:47 +03:00
def input_handler(fd):
stream = open(fd)
for line in stream: # CTRL+D, eli EOF, lopettaa
print('Line: {}'.format(line), end='')
parsed = json.loads(line)
source_id = parsed.get('source_id', '')
for chat_id in routingdict.get(source_id, {}):
if source_id == 'pandacraft':
if parsed['verb'] == 'joined':
updater.bot.send_message(chat_id=chat_id, text='Pandacraft: {} liittyi peliin'.format(parsed['player']))
else:
updater.bot.send_message(chat_id=chat_id, text='Pandacraft: {} poistui'.format(parsed['player']))
else:
updater.bot.send_message(chat_id=chat_id, text=line)
2017-06-10 20:02:53 +03:00
def main(token_file):
TG_TOKEN = open(token_file).read()
# Create the EventHandler and pass it your bot's token.
updater = Updater(TG_TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", halp))
dp.add_handler(CommandHandler("fuck", fok))
# YEE
dp.add_handler(CommandHandler("print_routes", print_routes))
dp.add_handler(CommandHandler("route", route, pass_args=True))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
2018-04-02 22:00:47 +03:00
dp.add_error_handler(error_callback)
2017-06-10 20:02:53 +03:00
# Start the Bot
updater.start_polling()
2018-04-02 22:00:47 +03:00
# Start input handler
fd = sys.stdin.fileno() # = 0
ih = Process(target=input_handler, args=(fd,))
ih.start()
print('Input handler started.')
ih.join()
2017-06-10 20:02:53 +03:00
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
2018-04-02 22:00:47 +03:00
print('Entering idle.')
2017-06-10 20:02:53 +03:00
updater.idle()
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv[1]))