fortunes-spam/telegram-bot/fortunes-spam-bot.py

71 lines
2.3 KiB
Python
Raw Normal View History

2018-08-18 18:43:47 +02:00
#!/usr/bin/env python3
"""Telegram bot for fortunes-spam.
Build it with: docker build -t fortunes-spam-bot .
Run it with something like: docker run -ti --rm -e SPAMBOT_TOKEN=your-telegram-token fortunes-spam-bot
2021-06-12 15:47:41 +02:00
Copyright 2018-2021 Davide Alberani <da@erlug.linux.it> Apache 2.0 license
2018-08-18 18:43:47 +02:00
"""
import os
import logging
import subprocess
from telegram.ext import Updater, CommandHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
2021-06-12 15:47:41 +02:00
EXTERNAL_VOL = '/fortunes'
2018-08-18 18:43:47 +02:00
def getSpam(section):
2021-06-12 15:47:41 +02:00
extPath = os.path.join(EXTERNAL_VOL, section)
if os.path.isfile(extPath):
section = extPath
2018-08-18 18:43:47 +02:00
cmd = ['fortune', '-o', section]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
try:
stdout = stdout.strip()
stdout = stdout.decode('utf8')
except:
return 'uh-oh: something was wrong with the encoding of the can\'s label; try again'
if process.returncode != 0:
return 'something terrible is happening: exit code: %s, stderr: %s' % (
process.returncode, stderr.decode('utf8'))
if not stdout:
return 'sadness: the spam can was empty; try again'
return stdout
2021-06-12 15:47:41 +02:00
def serve(section, update, context):
2018-08-18 18:43:47 +02:00
spam = getSpam(section)
2021-06-12 15:47:41 +02:00
logging.info('%s wants some spam; serving:\n%s' % (update.effective_user.username, spam))
2018-08-18 18:43:47 +02:00
update.message.reply_text(spam)
2021-06-12 15:47:41 +02:00
def en(update, context):
return serve('spam-o', update, context)
2018-08-18 18:43:47 +02:00
2021-06-12 15:47:41 +02:00
def it(update, context):
return serve('spam-ita-o', update, context)
2018-08-18 18:43:47 +02:00
2021-06-12 15:47:41 +02:00
def about(update, context):
logging.info('%s required more info' % update.effective_user.username)
2018-08-18 19:24:18 +02:00
update.message.reply_text('See https://github.com/alberanid/fortunes-spam')
2018-08-18 18:43:47 +02:00
if __name__ == '__main__':
2018-08-18 19:24:18 +02:00
if 'SPAMBOT_TOKEN' not in os.environ:
2018-08-18 18:43:47 +02:00
print("Please specify the Telegram token in the SPAMBOT_TOKEN environment variable")
logging.info('start serving delicious spam')
updater = Updater(os.environ['SPAMBOT_TOKEN'])
updater.dispatcher.add_handler(CommandHandler('en', en))
updater.dispatcher.add_handler(CommandHandler('it', it))
2018-08-18 19:24:18 +02:00
updater.dispatcher.add_handler(CommandHandler('about', about))
2018-08-18 18:43:47 +02:00
updater.start_polling()
updater.idle()