Browse Source

api update, minor refactoring

master
angerstoner 3 years ago
parent
commit
ddca1d4479
  1. 1
      .gitignore
  2. 2
      .idea/.gitignore
  3. 6
      .idea/inspectionProfiles/profiles_settings.xml
  4. 7
      .idea/misc.xml
  5. 8
      .idea/modules.xml
  6. 12
      .idea/schneiderbot-tg.iml
  7. 6
      .idea/vcs.xml
  8. 9
      mensa.py
  9. 1
      misc/commandlist
  10. 70
      reddit.py
  11. 54
      schneiderbot.py
  12. 12
      schneiderbot_twitter.py
  13. 9
      web_requests.py

1
.gitignore

@ -27,6 +27,7 @@ var/
*.egg-info/
.installed.cfg
*.egg
venv/
# PyInstaller
# Usually these files are written by a python script from a template

2
.idea/.gitignore

@ -0,0 +1,2 @@
# Default ignored files
/workspace.xml

6
.idea/inspectionProfiles/profiles_settings.xml

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
.idea/misc.xml

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (schneiderbot-tg)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/schneiderbot-tg.iml" filepath="$PROJECT_DIR$/.idea/schneiderbot-tg.iml" />
</modules>
</component>
</project>

12
.idea/schneiderbot-tg.iml

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.9 (schneiderbot-tg)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>

6
.idea/vcs.xml

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

9
mensa.py

@ -1,6 +1,7 @@
import datetime
from telegram import ParseMode
from telegram import ParseMode, Update
import requests
from telegram.ext import CallbackContext
DISABLED_GROUPS = [-1001301570558]
@ -70,11 +71,11 @@ MODES = {
}
def linux_mensa(bot, update):
mensa(bot, update, ["linux"])
def linux_mensa(update: Update, context: CallbackContext):
mensa(update, context, ["linux"])
def mensa(bot, update, args):
def mensa(update: Update, context: CallbackContext, args: list[str]):
if update.message.chat_id in DISABLED_GROUPS:
return
which = "zentral"

1
misc/commandlist

@ -1,6 +1,7 @@
mensa - [TAG/full/veggy/fleisch/fisch] essen in der mensa, filter möglich
cat - random cat image (using reddit.com/r/catpictures)
dog - random dog image (using reddit.com/r/dogpictures)
drillcat - random drillcat image (using reddit.com/r/drillcats)
hamster - random dog image (using reddit.com/r/hamsters)
wrongdog - random wrongdog image (using reddit.com/r/whatswrongwithyourdog)
catdog - catdog pic

70
reddit.py

@ -1,6 +1,8 @@
import praw
from prawcore import exceptions
import requests
from prawcore import exceptions
from telegram import Update
from telegram.ext import CallbackContext
four_twenty_groups = []
@ -35,9 +37,9 @@ def get_reddit_post(sub, is_image_post=False):
post = sub.random()
except exceptions.NotFound:
return "Geile, gib gültiges Sub"
return "Ungültiges Sub :("
except exceptions.Forbidden:
return "Geile, gib freies Sub"
return "Privates/Gesperrtes Sub :("
except Exception as e:
return e
@ -50,66 +52,54 @@ def get_reddit_post(sub, is_image_post=False):
post = sub.random()
tries += 1
if tries >= 5:
return "Geile, gib Sub mit Bildern (über 5 Fehlversuche)"
return "Keine Bilder gefunden (über 5 Fehlversuche)"
return post
def toggle_four_twenty(bot, update):
chat_id = update.message.chat_id
if chat_id in four_twenty_groups:
four_twenty_groups.remove(chat_id)
update.message.reply_text("You killed the fire!")
else:
four_twenty_groups.append(update.message.chat_id)
update.message.reply_text("420 blaze it!")
def four_twenty(bot, update):
for group_id in four_twenty_groups:
post = get_reddit_post('trees', True)
bot.send_photo(chat_id=group_id, photo=post.url, caption=post.title)
def wrong_dog(bot, update):
reddit_img(bot, update, ['whatswrongwithyourdog'])
def wrong_dog(update: Update, context: CallbackContext):
context.args = ['whatswrongwithyourdog']
reddit_img(update, context)
def hamster(bot, update):
reddit_img(bot, update, ['hamsters'])
def hamster(update: Update, context: CallbackContext):
context.args = ['hamsters']
reddit_img(update, context)
def drillcat(bot, update):
reddit_img(bot, update, ['drillcats'])
def drillcat(update: Update, context: CallbackContext):
context.args = ['drillcats']
reddit_img(update, context)
def cat(bot, update):
reddit_img(bot, update, ['catpictures'])
def cat(update: Update, context: CallbackContext):
context.args = ['catpictures']
reddit_img(update, context)
def dog(bot, update):
reddit_img(bot, update, ['dogpictures'])
def dog(update: Update, context: CallbackContext):
context.args = ['dogpictures']
reddit_img(update, context)
def reddit(bot, update, args):
if not args:
update.message.reply_text("Geile, sag sub")
def reddit(update: Update, context: CallbackContext):
if not context.args:
update.message.reply_text("Bitte Sub angeben")
return
sub = args[0]
sub = context.args[0]
update.message.reply_text(get_reddit_post(sub).url)
def reddit_img(bot, update, args):
if not args:
update.message.reply_text("Geile, sag sub")
def reddit_img(update: Update, context: CallbackContext):
if not context.args:
update.message.reply_text("Bitte Sub angeben")
return
sub = args[0]
sub = context.args[0]
post = get_reddit_post(sub, True)
try:
bot.send_photo(chat_id=update.message.chat_id, photo=post.url)
context.bot.send_photo(chat_id=update.message.chat_id, photo=post.url)
return
except AttributeError:
update.message.reply_text(post)

54
schneiderbot.py

@ -1,14 +1,13 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import logging
import random
from telegram import ParseMode
from telegram.ext import Updater, CommandHandler
from telegram import ParseMode, Update
from telegram.ext import Updater, CommandHandler, CallbackContext
from web_requests import send_coding_love_gif, send_wiki_how_article
from reddit import wrong_dog, hamster, reddit, reddit_img, toggle_four_twenty, four_twenty, cat, dog, drillcat
from reddit import wrong_dog, hamster, reddit, reddit_img, cat, dog, drillcat
from schneiderbot_twitter import toggle_pepito_for_group, check_pepito_and_post_auto, check_pepito_and_post_manually
from db import Db
from mensa import mensa, linux_mensa
@ -35,15 +34,14 @@ with open("res/simon.txt", "r") as tmp_file:
# 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):
def start(update: Update, context: CallbackContext):
"""Was ist das hier für eins Bot?"""
update.message.reply_text("""Hallo, ich bin ein Bot.
Ich liefere tolle Informationen über die Mensa, Katzenbilder, Hundebilder und andere _tolle_ Sachen. Die Infos kommen von
https://mensa.schneider-hosting.de
Ich liefere tolle Informationen über die Mensa, Katzenbilder, Hundebilder und andere _tolle_ Sachen.
Mhmm, lecker. Guten Appetit!""", parse_mode=ParseMode.MARKDOWN)
def help(bot, update):
def help(update: Update, context: CallbackContext):
"""Send a message when the command /help is issued."""
reply_text = """Commands:
*Mensa*:
@ -77,7 +75,7 @@ def help(bot, update):
update.message.reply_text(reply_text, parse_mode=ParseMode.MARKDOWN)
def kill(bot, update, sudocall=False):
def kill(update: Update, context: CallbackContext, sudocall=False):
"""kill me pls"""
db = Db()
user = update.message.from_user.first_name
@ -95,7 +93,7 @@ def kill(bot, update, sudocall=False):
update.message.reply_text(message)
def revive(bot, update, sudocall=False):
def revive(update: Update, context: CallbackContext, sudocall=False):
"""unkill me pls"""
db = Db()
user = update.message.from_user.first_name
@ -115,56 +113,56 @@ SUDO_CMDS = {
}
def graveyard(bot, update):
def graveyard(update: Update, context: CallbackContext):
"""List the dead"""
db = Db()
update.message.reply_text("Here are the dead people:\n%s" % db.get_dead_bodies(update.message.chat_id))
def sudo(bot, update, args):
def sudo(update: Update, context: CallbackContext, args):
"""for real"""
if not args:
update.message.reply_text("Unknown command")
return
for arg in args:
if arg in SUDO_CMDS:
SUDO_CMDS[arg](bot, update, True)
SUDO_CMDS[arg](update, context, True)
else:
update.message.reply_text("Unknown command")
def send_cat_dog(bot, update):
def send_cat_dog(update: Update, context: CallbackContext):
"""Best of both worlds!"""
catdog = "https://upload.wikimedia.org/wikipedia/en/6/64/CatDog.jpeg"
bot.send_photo(chat_id=update.message.chat_id, photo=catdog)
context.bot.send_photo(chat_id=update.message.chat_id, photo=catdog)
def magie(bot, update):
def magie(update: Update, context: CallbackContext):
"""MAGIEEEEEE"""
rand = random.SystemRandom()
update.message.reply_text(STOLL[rand.randrange(0, len(STOLL), 1)])
def manta(bot, update):
def manta(update: Update, context: CallbackContext):
"""Boah ey, geile Karre!"""
rand = random.SystemRandom()
update.message.reply_text(MANTA[rand.randrange(0, len(MANTA), 1)])
def goodlife(bot, update):
def goodlife(update: Update, context: CallbackContext):
"""GOOD LIFE MY A..."""
rand = random.SystemRandom()
update.message.reply_text(GOOD_LIFE[rand.randrange(0, len(GOOD_LIFE), 1)])
def shrug(bot, update):
def shrug(update: Update, context: CallbackContext):
"""SHRUG"""
update.message.reply_text("¯\_(ツ)_/¯")
def simon(bot, update, args):
"KAUF DIR N HUND"
name = "@thedailysimon"
def simon(update: Update, context: CallbackContext, args):
"""KAUF DIR N HUND"""
name = "Simon"
if len(args) > 0:
name = args[0]
rand = random.SystemRandom()
@ -174,14 +172,14 @@ def simon(bot, update, args):
% (name, animal))
def echo(bot, update):
def echo(update: Update, context: CallbackContext):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(bot, update, error):
def error(update: Update, context: CallbackContext):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
logger.warning('Update "%s" caused error "%s"', update, context.error)
def init_commands(dp):
@ -207,11 +205,10 @@ def init_commands(dp):
dp.add_handler(CommandHandler("wrongdog", wrong_dog))
dp.add_handler(CommandHandler("hamster", hamster))
dp.add_handler(CommandHandler("drillcat", drillcat))
dp.add_handler(CommandHandler("reddit", reddit, pass_args=True))
dp.add_handler(CommandHandler("reddit_img", reddit_img, pass_args=True))
dp.add_handler(CommandHandler("reddit", reddit))
dp.add_handler(CommandHandler("reddit_img", reddit_img))
dp.add_handler(CommandHandler("pepito", check_pepito_and_post_manually))
dp.add_handler(CommandHandler("tpepito", toggle_pepito_for_group))
dp.add_handler(CommandHandler("lightitup", toggle_four_twenty))
def main():
@ -227,7 +224,6 @@ def main():
init_commands(dp)
jq.run_repeating(check_pepito_and_post_auto, interval=180, first=0)
jq.run_daily(four_twenty, datetime.time(4, 20, 0), days=(0, 1, 2, 3, 4, 5, 6))
# on different commands - answer in Telegram

12
schneiderbot_twitter.py

@ -1,4 +1,6 @@
import twitter
from telegram import Update
from telegram.ext import CallbackContext
pepito_id = 333923305
last_status = None
@ -18,7 +20,7 @@ def get_twitter_instance():
access_token_secret=twitter_config['access_token_secret'])
def toggle_pepito_for_group(bot, update):
def toggle_pepito_for_group(update: Update, context: CallbackContext):
global pepito_groups
chat_id = update.message.chat_id
@ -30,24 +32,24 @@ def toggle_pepito_for_group(bot, update):
update.message.reply_text("Pepito is now enabled!")
def check_pepito_and_post_auto(bot, update):
def check_pepito_and_post_auto(context: CallbackContext):
api = get_twitter_instance()
current_status = api.GetUserTimeline(pepito_id)[0]
global last_status
if last_status is None or last_status.AsDict()['id'] != current_status.AsDict()['id']:
for group_id in pepito_groups:
bot.send_message(chat_id=group_id, text=current_status.AsDict()['text'])
context.bot.send_message.send_message(chat_id=group_id, text=current_status.AsDict()['text'])
last_status = current_status
def check_pepito_and_post_manually(bot, update):
def check_pepito_and_post_manually(update: Update, context: CallbackContext):
api = get_twitter_instance()
current_status = api.GetUserTimeline(pepito_id)[0]
global last_status
if last_status.AsDict()['id'] != current_status.AsDict()['id']:
for group_id in pepito_groups:
bot.send_message(chat_id=group_id, text=current_status.AsDict()['text'])
context.bot.send_message(chat_id=group_id, text=current_status.AsDict()['text'])
last_status = current_status
else:
update.message.reply_text(current_status.AsDict()['text'])

9
web_requests.py

@ -2,13 +2,16 @@ import requests
import re
import html
from telegram import Update
from telegram.ext import CallbackContext
urls = {
"codinglove": "https://thecodinglove.com/",
"wikihow": "https://de.wikihow.com/Spezial:Randomizer"
}
def send_coding_love_gif(bot, update):
def send_coding_love_gif(update: Update, context: CallbackContext):
random_url = re.search('href="(.*)".*\n.*\n.*random\( \)', requests.get(urls["codinglove"]).text).group(1)
random_page_content = requests.get(random_url)
@ -23,13 +26,13 @@ def send_coding_love_gif(bot, update):
if gif_match:
gif_url = gif_match.group(1)
bot.send_animation(chat_id=update.message.chat_id, animation=gif_url, caption=caption)
context.bot.send_animation(chat_id=update.message.chat_id, animation=gif_url, caption=caption)
else:
update.message.reply_text("Error fetching image: {} ¯\_(ツ)_/¯".format(random_url))
def send_wiki_how_article(bot, update):
def send_wiki_how_article(update: Update, context: CallbackContext):
random_howto = requests.get(urls["wikihow"])
howto_title = re.search('<title>(.*)</title>', random_howto.text).group(1)
howto_url = re.search('<link rel="canonical" href="(.*)".*/>', random_howto.text).group(1)

Loading…
Cancel
Save