159 lines
4.9 KiB
Python
159 lines
4.9 KiB
Python
#!/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
|
|
import logging
|
|
from pprint import pformat
|
|
from multiprocessing import Process
|
|
|
|
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
|
|
from telegram.error import (TelegramError, Unauthorized, BadRequest,
|
|
TimedOut, ChatMigrated, NetworkError)
|
|
|
|
# Enable logging
|
|
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
level=logging.INFO)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
# 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)
|
|
|
|
|
|
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)
|
|
|
|
|
|
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):
|
|
update.message.reply_text(pformat(routingdict))
|
|
|
|
|
|
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)
|
|
|
|
|
|
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
|
|
dp.add_error_handler(error_callback)
|
|
|
|
# Start the Bot
|
|
updater.start_polling()
|
|
|
|
# Start input handler
|
|
fd = sys.stdin.fileno() # = 0
|
|
ih = Process(target=input_handler, args=(fd,))
|
|
ih.start()
|
|
|
|
print('Input handler started.')
|
|
ih.join()
|
|
|
|
# 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.
|
|
print('Entering idle.')
|
|
updater.idle()
|
|
|
|
return 0
|
|
|
|
if __name__ == '__main__':
|
|
import sys
|
|
sys.exit(main(sys.argv[1]))
|
|
|