1
0
Fork 0
mirror of https://github.com/Findus23/nonsense.git synced 2024-09-19 16:03:50 +02:00
nonsense/telegramBot.py

172 lines
5.2 KiB
Python
Raw Normal View History

2016-11-08 16:52:15 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
2016-11-09 10:55:25 +01:00
import datetime
2016-11-09 09:43:22 +01:00
import logging
2016-11-08 19:02:22 +01:00
from uuid import uuid4
2017-12-11 21:14:03 +01:00
2016-11-09 09:43:22 +01:00
import yaml
2016-11-08 19:02:22 +01:00
from telegram import InlineQueryResultArticle
from telegram import InputTextMessageContent
from telegram.ext import InlineQueryHandler
2017-12-11 21:14:03 +01:00
from telegram.ext import Updater, CommandHandler
2016-11-08 16:52:15 +01:00
import config
import generate
2016-11-08 19:02:22 +01:00
subscriptions = dict()
2016-11-08 16:52:15 +01:00
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
2017-12-13 20:01:44 +01:00
level=logging.INFO)
2016-11-08 16:52:15 +01:00
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 help(bot, update):
update.message.reply_text("Hier steht der Hilfetext!")
2016-11-08 19:02:22 +01:00
def single(bot, update):
update.message.reply_text(generate.get_description())
def subscribe_notification(bot, job):
bot.sendMessage(job.context, text=generate.get_description())
def subscribe(bot, update, job_queue):
"""Adds a job to the queue"""
chat_id = update.message.chat_id
# Add job to queue
2016-11-10 08:11:27 +01:00
if chat_id in subscriptions:
update.message.reply_text('You are already subscribed')
return
2017-12-11 21:14:03 +01:00
job = job_queue.run_daily(subscribe_notification,
context=chat_id,
2017-12-13 20:00:34 +01:00
time=datetime.datetime.now().replace(minute=0, hour=8, second=0)
+ datetime.timedelta(days=1))
2016-11-08 19:02:22 +01:00
subscriptions[chat_id] = job
update.message.reply_text('Successfully subscribed')
def unsubscribe(bot, update):
"""Deletes a job"""
chat_id = update.message.chat_id
if chat_id not in subscriptions:
update.message.reply_text('You have no subscription')
return
# Add job to queue
job = subscriptions[chat_id]
job.schedule_removal()
del subscriptions[chat_id]
update.message.reply_text('Successfully unsubscribed')
2016-11-08 16:52:15 +01:00
def multiple(bot, update, args):
try:
descriptions = []
print(args)
count = int(args[0])
2016-11-09 09:43:22 +01:00
if count > 50:
update.message.reply_text(str(count) + ' > 50')
2016-11-08 16:52:15 +01:00
return
for _ in range(count):
descriptions.append("+++ " + generate.get_description() + " +++")
update.message.reply_text("\n".join(descriptions))
except (IndexError, ValueError):
update.message.reply_text('Usage: /multiple <count>')
def error(bot, update, error):
2017-12-10 14:18:19 +01:00
logger.warning('Update "%s" caused error "%s"' % (update, error))
2016-11-08 16:52:15 +01:00
2016-11-09 09:43:22 +01:00
def inlinequery(bot, update):
if update.inline_query.query == "":
count = 3
else:
count = int(update.inline_query.query)
results = list()
if count > 50:
count = 50
for i in range(count):
description = generate.get_description()
results.append(InlineQueryResultArticle(id=uuid4(),
title=description,
input_message_content=InputTextMessageContent(description)))
update.inline_query.answer(results)
def startup(job_queue):
with open("save.yaml") as json_file:
save = yaml.load(json_file)
for s in save["subscriptions"]:
2017-12-11 21:14:03 +01:00
job = job_queue.run_daily(subscribe_notification, context=s,
2017-12-13 20:00:34 +01:00
time=datetime.datetime.now().replace(minute=0, hour=8, second=0)
+ datetime.timedelta(days=1))
2016-11-09 09:43:22 +01:00
subscriptions[s] = job
2016-11-10 08:11:27 +01:00
def shutdown(a=None, b=None):
2016-11-09 09:43:22 +01:00
print("------------------------------------------------------------------------") #
save = {
"subscriptions": []
}
2017-12-11 21:14:03 +01:00
print(subscriptions)
2016-11-09 09:43:22 +01:00
for s in subscriptions:
save["subscriptions"].append(s)
with open("save.yaml", 'w') as stream:
yaml.dump(save, stream, default_flow_style=False)
2016-11-08 16:52:15 +01:00
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(config.telegram_bot_token)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", help))
dp.add_handler(CommandHandler("help", help))
2016-11-08 19:02:22 +01:00
dp.add_handler(CommandHandler("single", single))
2016-11-08 16:52:15 +01:00
dp.add_handler(CommandHandler("multiple", multiple, pass_args=True))
2016-11-08 19:02:22 +01:00
# dp.add_handler(CommandHandler("single", subscribe_notification))
dp.add_handler(CommandHandler("subscribe", subscribe, pass_job_queue=True))
dp.add_handler(CommandHandler("unsubscribe", unsubscribe))
2016-11-08 16:52:15 +01:00
2016-11-10 08:11:27 +01:00
dp.add_handler(CommandHandler("save", shutdown))
2016-11-08 16:52:15 +01:00
# on noncommand i.e message - echo the message on Telegram
2016-11-10 08:17:15 +01:00
# dp.add_handler(MessageHandler(Filters.text, single))
2016-11-08 16:52:15 +01:00
2016-11-09 09:43:22 +01:00
dp.add_handler(InlineQueryHandler(inlinequery))
2016-11-08 16:52:15 +01:00
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
2016-11-09 09:43:22 +01:00
startup(updater.job_queue)
2016-11-08 16:52:15 +01:00
# Run the bot until the you presses 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.
updater.idle()
2016-11-09 09:43:22 +01:00
shutdown()
2016-11-08 16:52:15 +01:00
if __name__ == '__main__':
main()