far better structure, more modular
This commit is contained in:
parent
a704622f2b
commit
b2bb728c09
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,5 +1,5 @@
|
|||||||
# API-Key (keep secret at all times)
|
# API-Key (keep secret at all times)
|
||||||
key.py
|
keys.py
|
||||||
|
|
||||||
# Cookies
|
# Cookies
|
||||||
.google-cookie
|
.google-cookie
|
||||||
|
1
api/__init__.py
Normal file
1
api/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Placeholder
|
20
api/google.py
Normal file
20
api/google.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import googlesearch
|
||||||
|
|
||||||
|
|
||||||
|
def query(params):
|
||||||
|
param_string = ""
|
||||||
|
for word in params:
|
||||||
|
param_string += word + "+"
|
||||||
|
param_string = param_string[:-1]
|
||||||
|
search_url = "https://google.com/search?q=" + param_string
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = googlesearch.search(param_string.replace("+"," ") ,num=5,start=0,stop=5)
|
||||||
|
send_string = "Google search for <b>" + param_string.replace("+"," ") + "</b>:\n"
|
||||||
|
for url in res:
|
||||||
|
send_string += url + "\n\n"
|
||||||
|
send_string += "Search url:\n" + search_url
|
||||||
|
except:
|
||||||
|
send_string = "Search url:\n" + search_url
|
||||||
|
|
||||||
|
return send_string
|
29
api/reddit.py
Normal file
29
api/reddit.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import praw
|
||||||
|
try:
|
||||||
|
import api.keys as keys
|
||||||
|
except:
|
||||||
|
import keys
|
||||||
|
|
||||||
|
stream = praw.Reddit(client_id = keys.reddit_id, client_secret = keys.reddit_secret, user_agent=keys.reddit_user_agent)
|
||||||
|
|
||||||
|
def get_top_text(subreddit, number):
|
||||||
|
message = ""
|
||||||
|
try:
|
||||||
|
for submission in stream.subreddit(subreddit).hot(limit=number):
|
||||||
|
if not submission.stickied:
|
||||||
|
message += "<b>" + submission.title + "</b>" + "\n" + submission.selftext + "\n\n\n"
|
||||||
|
return message
|
||||||
|
except:
|
||||||
|
return "Api call failed, sorry"
|
||||||
|
|
||||||
|
|
||||||
|
def get_top_image(subreddit, number):
|
||||||
|
images = []
|
||||||
|
try:
|
||||||
|
for submission in stream.subreddit(subreddit).hot(limit=number):
|
||||||
|
if not submission.stickied:
|
||||||
|
t = {"image": submission.url, "caption": submission.title}
|
||||||
|
images.append(t)
|
||||||
|
return images
|
||||||
|
except:
|
||||||
|
return ["Api call failed, sorry"]
|
156
api/telegram.py
Normal file
156
api/telegram.py
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
import emoji
|
||||||
|
import requests
|
||||||
|
import Levenshtein as lev
|
||||||
|
|
||||||
|
import api.keys
|
||||||
|
|
||||||
|
|
||||||
|
class TelegramIO():
|
||||||
|
def __init__(self, persistence, commands):
|
||||||
|
"""Inits the Telegram-Interface
|
||||||
|
"""
|
||||||
|
self.base_url = "https://api.telegram.org/bot" + api.keys.telegram_api + "/"
|
||||||
|
self.persistence = persistence
|
||||||
|
self.commands = commands
|
||||||
|
# Dynamic variables for answering
|
||||||
|
self.chat_id = ""
|
||||||
|
self.offset = 0
|
||||||
|
self.message_id = ""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
########################################################################
|
||||||
|
"""Helper-Functions"""
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_updates(self):
|
||||||
|
""""""
|
||||||
|
update_url = self.base_url + "getUpdates"
|
||||||
|
data = {"offset":self.offset}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = requests.post(update_url,data=data)
|
||||||
|
result = result.json()["result"]
|
||||||
|
except:
|
||||||
|
result = ""
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def handle_result(self, result):
|
||||||
|
"""Inspects the message and reacts accordingly. Can easily be extended"""
|
||||||
|
for message_data in result:
|
||||||
|
message_read = self.persistence.read("messages_read")
|
||||||
|
self.persistence.write("messages_read", message_read + 1)
|
||||||
|
self.offset = message_data["update_id"] + 1
|
||||||
|
message = message_data["message"]
|
||||||
|
self.message_id = message["message_id"]
|
||||||
|
self.chat_id = message["chat"]["id"]
|
||||||
|
author = message["from"]
|
||||||
|
|
||||||
|
chat_members = self.persistence.read("chat_members")
|
||||||
|
if str(author["id"]) not in chat_members:
|
||||||
|
name = ""
|
||||||
|
if "first_name" in author:
|
||||||
|
name += author["first_name"] + " "
|
||||||
|
if "last_name" in author:
|
||||||
|
name += author["last_name"]
|
||||||
|
if len(name) == 0:
|
||||||
|
name += "anonymous"
|
||||||
|
chat_members[author["id"]] = name
|
||||||
|
self.persistence.write("chat_members", chat_members)
|
||||||
|
self.send_message("Welcome to this chat " + name + "!")
|
||||||
|
|
||||||
|
if "text" in message:
|
||||||
|
print("Chat said: ", emoji.demojize(message["text"]))
|
||||||
|
|
||||||
|
if "entities" in message:
|
||||||
|
for entry in message["entities"]:
|
||||||
|
if entry["type"] == "bot_command":
|
||||||
|
return self.handle_command(message["text"][1:])
|
||||||
|
|
||||||
|
elif "photo" in message:
|
||||||
|
print("Photo received, what do I do?")
|
||||||
|
|
||||||
|
|
||||||
|
def handle_command(self, command):
|
||||||
|
"""Handles commands and stuff, using a bash-like syntax:
|
||||||
|
/[command] [argument 1] [argument 2] ...
|
||||||
|
"""
|
||||||
|
full = command.split(" ")
|
||||||
|
command = self.fuzzy_match_command(full[0])
|
||||||
|
if len(command) != 1:
|
||||||
|
if command[0] == "EXACT":
|
||||||
|
self.persistence.increment("commands_executed")
|
||||||
|
return command[1], full[1:]
|
||||||
|
else:
|
||||||
|
send = "Did you mean <code>" + command[1] + "</code>"
|
||||||
|
for i in range(2,len(command)):
|
||||||
|
send += " or <code>" + command[1] + "</code>"
|
||||||
|
send += "?"
|
||||||
|
self.send_message(send)
|
||||||
|
else:
|
||||||
|
self.send_message("Command <code>" + full[0] + "</code> not found. Please try again.")
|
||||||
|
|
||||||
|
return "nothing", "happened"
|
||||||
|
|
||||||
|
def fuzzy_match_command(self, input):
|
||||||
|
matches = ["not exact"]
|
||||||
|
for command in self.commands.keys():
|
||||||
|
if lev.ratio(input.lower(),command) > 0.8:
|
||||||
|
matches.append(command)
|
||||||
|
if lev.ratio(input.lower(),command) == 1:
|
||||||
|
return ["EXACT", command]
|
||||||
|
|
||||||
|
return matches
|
||||||
|
|
||||||
|
|
||||||
|
def send_thinking_note(self):
|
||||||
|
data = {
|
||||||
|
"chat_id" : self.chat_id,
|
||||||
|
"action" : "typing",
|
||||||
|
}
|
||||||
|
send_url = self.base_url + "sendChatAction"
|
||||||
|
try:
|
||||||
|
r = requests.post(send_url, data=data)
|
||||||
|
except:
|
||||||
|
print("Could not show that I'm thinking =(")
|
||||||
|
|
||||||
|
|
||||||
|
def send_message(self, message):
|
||||||
|
print("SENDING: " + emoji.demojize(message))
|
||||||
|
|
||||||
|
data = {
|
||||||
|
'chat_id': self.chat_id,
|
||||||
|
'text': emoji.emojize(message),
|
||||||
|
"parse_mode": "HTML",
|
||||||
|
"reply_to_message_id" : self.message_id,
|
||||||
|
}
|
||||||
|
send_url = self.base_url + "sendMessage"
|
||||||
|
try:
|
||||||
|
r = requests.post(send_url, data=data)
|
||||||
|
except:
|
||||||
|
log = self.persistence.read("log")
|
||||||
|
log.append(str(datetime.datetime.now()) + " - did not send:\n" + message)
|
||||||
|
self.persistence.write("log", log)
|
||||||
|
|
||||||
|
self.persistence.increment("messages_sent")
|
||||||
|
|
||||||
|
def send_photo(self, url, caption):
|
||||||
|
print("SENDING PHOTO: " + url)
|
||||||
|
data = {
|
||||||
|
'chat_id': self.chat_id,
|
||||||
|
'photo': url,
|
||||||
|
"parse_mode": "HTML",
|
||||||
|
"reply_to_message_id" : self.message_id,
|
||||||
|
'caption' : caption,
|
||||||
|
}
|
||||||
|
send_url = self.base_url + "sendPhoto"
|
||||||
|
try:
|
||||||
|
r = requests.post(send_url, data=data)
|
||||||
|
except:
|
||||||
|
log = self.persistence.read("log")
|
||||||
|
log.append(str(datetime.datetime.now()) + " - did not send:\n" + url)
|
||||||
|
self.persistence.write("log", log)
|
||||||
|
|
||||||
|
self.persistence.increment("photos_sent")
|
28
api/weather.py
Normal file
28
api/weather.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import requests
|
||||||
|
import api.keys
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
def show_weather(location):
|
||||||
|
url = "https://api.openweathermap.org/data/2.5/onecall?"
|
||||||
|
data = {"lat" : location[0], "lon" : location[1], "exclude" : "minutely,hourly", "appid" : api.keys.weather_api, "units" : "metric"}
|
||||||
|
today = datetime.datetime.today().weekday()
|
||||||
|
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
weather = requests.get(url,params=data).json()
|
||||||
|
except:
|
||||||
|
return "Query failed, it's my fault, I'm sorry :sad:"
|
||||||
|
|
||||||
|
|
||||||
|
categories = {"Clouds": ":cloud:", "Rain": ":cloud_with_rain:", "Thunderstorm": "thunder_cloud_rain", "Drizzle": ":droplet:", "Snow": ":cloud_snow:", "Clear": ":sun:", "Mist": "Mist", "Smoke": "Smoke", "Haze": "Haze", "Dust": "Dust", "Fog": "Fog", "Sand": "Sand", "Dust": "Dust", "Ash": "Ash", "Squall": "Squall", "Tornado": "Tornado",}
|
||||||
|
|
||||||
|
now = weather["current"]
|
||||||
|
message = "<b>Today:</b> " + categories[now["weather"][0]["main"]] + "\n"
|
||||||
|
message += ":thermometer: " + str(int(now["temp"])) + "°\n\n"
|
||||||
|
|
||||||
|
for i, day in enumerate(weather["daily"]):
|
||||||
|
|
||||||
|
message += "<b>" + days[(today + i + 1) % 7] + ":</b> " + categories[day["weather"][0]["main"]] + "\n"
|
||||||
|
message += ":thermometer: :fast_down_button: " + str(int(day["temp"]["min"])) + "° , :thermometer: :fast_up_button: " + str(int(day["temp"]["max"])) + "°\n\n"
|
||||||
|
|
||||||
|
return message
|
243
main.py
243
main.py
@ -1,19 +1,16 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
import key
|
from api import telegram, google, reddit, weather
|
||||||
|
from persistence import rw as pvars
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import time
|
import time
|
||||||
import json
|
import json
|
||||||
import datetime
|
import datetime
|
||||||
import googlesearch
|
|
||||||
import emoji
|
import emoji
|
||||||
import Levenshtein as lev
|
|
||||||
|
|
||||||
|
|
||||||
from persistence import PersistentVars
|
|
||||||
|
|
||||||
class ChatBot():
|
class ChatBot():
|
||||||
|
""""""
|
||||||
def __init__(self, name, version):
|
def __init__(self, name, version):
|
||||||
"""Inits the Bot with a few conf. vars
|
"""Inits the Bot with a few conf. vars
|
||||||
Args: -> name:str - Name of the bot
|
Args: -> name:str - Name of the bot
|
||||||
@ -21,23 +18,14 @@ class ChatBot():
|
|||||||
-> version:str - Version number
|
-> version:str - Version number
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self.base_url = "https://api.telegram.org/bot" + key.telegram_api + "/"
|
|
||||||
self.version = version
|
self.version = version
|
||||||
self.name = name
|
self.name = name
|
||||||
|
|
||||||
# Persistent variable
|
# Persistent variable
|
||||||
self.persistence = PersistentVars("permanent_vars.json")
|
self.persistence = pvars.Variables("persistence/permanent_vars.json")
|
||||||
|
|
||||||
# Uptime counter
|
# Uptime counter
|
||||||
self.start_time = datetime.datetime.now()
|
self.start_time = datetime.datetime.now()
|
||||||
self.persistence.write("reboots", self.persistence.read("reboots")+1)
|
self.persistence.increment("reboots")
|
||||||
|
|
||||||
|
|
||||||
# Dynamic variables for answering
|
|
||||||
self.chat_id = ""
|
|
||||||
self.offset = 0
|
|
||||||
self.message_id = ""
|
|
||||||
|
|
||||||
|
|
||||||
# Available commands
|
# Available commands
|
||||||
self.commands = {
|
self.commands = {
|
||||||
@ -53,6 +41,8 @@ class ChatBot():
|
|||||||
"bot_do_all" : self.bot_do_all,
|
"bot_do_all" : self.bot_do_all,
|
||||||
"zvv" : self.bot_zvv,
|
"zvv" : self.bot_zvv,
|
||||||
"cronjob" : self.bot_cronjob,
|
"cronjob" : self.bot_cronjob,
|
||||||
|
"joke" : self.bot_tell_joke,
|
||||||
|
"meme" : self.bot_send_meme,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -95,132 +85,22 @@ class ChatBot():
|
|||||||
"9" : ":keycap_digit_nine:",
|
"9" : ":keycap_digit_nine:",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.telegram = telegram.TelegramIO(self.persistence, self.commands)
|
||||||
|
|
||||||
self.message_loop()
|
self.message_loop()
|
||||||
|
|
||||||
########################################################################
|
|
||||||
"""Helper-Functions"""
|
|
||||||
|
|
||||||
def message_loop(self):
|
def message_loop(self):
|
||||||
""""""
|
"""Calls the telegram entity regularly to check for activity"""
|
||||||
while(True):
|
while(True):
|
||||||
result = self.fetch_updates()
|
result = self.telegram.fetch_updates()
|
||||||
if len(result) != 0:
|
if len(result) != 0:
|
||||||
self.handle_result(result)
|
command, params = self.telegram.handle_result(result)
|
||||||
|
if command != "nothing":
|
||||||
|
self.commands[command](params)
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|
||||||
|
|
||||||
def fetch_updates(self):
|
|
||||||
""""""
|
|
||||||
update_url = self.base_url + "getUpdates"
|
|
||||||
data = {"offset":self.offset}
|
|
||||||
|
|
||||||
try:
|
|
||||||
result = requests.post(update_url,data=data)
|
|
||||||
result = result.json()["result"]
|
|
||||||
except:
|
|
||||||
result = ""
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def handle_result(self, result):
|
|
||||||
"""Inspects the message and reacts accordingly. Can easily be extended"""
|
|
||||||
for message_data in result:
|
|
||||||
message_read = self.persistence.read("message_read")
|
|
||||||
self.persistence.write("message_read", message_read + 1)
|
|
||||||
self.offset = message_data["update_id"] + 1
|
|
||||||
message = message_data["message"]
|
|
||||||
self.message_id = message["message_id"]
|
|
||||||
self.chat_id = message["chat"]["id"]
|
|
||||||
author = message["from"]
|
|
||||||
|
|
||||||
chat_members = self.persistence.read("chat_members")
|
|
||||||
if str(author["id"]) not in chat_members:
|
|
||||||
name = ""
|
|
||||||
if "first_name" in author:
|
|
||||||
name += author["first_name"] + " "
|
|
||||||
if "last_name" in author:
|
|
||||||
name += author["last_name"]
|
|
||||||
if len(name) == 0:
|
|
||||||
name += "anonymous"
|
|
||||||
chat_members[author["id"]] = name
|
|
||||||
self.persistence.write("chat_members", chat_members)
|
|
||||||
self.send_message("Welcome to this chat " + name + "!")
|
|
||||||
|
|
||||||
if "text" in message:
|
|
||||||
print("Chat said: ", emoji.demojize(message["text"]))
|
|
||||||
|
|
||||||
if "entities" in message:
|
|
||||||
for entry in message["entities"]:
|
|
||||||
if entry["type"] == "bot_command":
|
|
||||||
self.handle_command(message["text"][1:])
|
|
||||||
|
|
||||||
elif "photo" in message:
|
|
||||||
print("Photo received, what do I do?")
|
|
||||||
|
|
||||||
|
|
||||||
def handle_command(self, command):
|
|
||||||
"""Handles commands and stuff, using a bash-like syntax:
|
|
||||||
/[command] [argument 1] [argument 2] ...
|
|
||||||
"""
|
|
||||||
full = command.split(" ")
|
|
||||||
command = self.fuzzy_match_command(full[0])
|
|
||||||
if len(command) != 1:
|
|
||||||
if command[0] == "EXACT":
|
|
||||||
self.commands[command[1]](full[1:])
|
|
||||||
else:
|
|
||||||
send = "Did you mean <code>" + command[1] + "</code>"
|
|
||||||
for i in range(2,len(command)):
|
|
||||||
send += " or <code>" + command[1] + "</code>"
|
|
||||||
send += "?"
|
|
||||||
self.send_message(send)
|
|
||||||
else:
|
|
||||||
self.send_message("Command <code>" + full[0] + "</code> not found. Please try again.")
|
|
||||||
|
|
||||||
|
|
||||||
def fuzzy_match_command(self, input):
|
|
||||||
matches = ["not exact"]
|
|
||||||
for command in self.commands.keys():
|
|
||||||
if lev.ratio(input.lower(),command) > 0.8:
|
|
||||||
matches.append(command)
|
|
||||||
if lev.ratio(input.lower(),command) == 1:
|
|
||||||
return ["EXACT", command]
|
|
||||||
|
|
||||||
return matches
|
|
||||||
|
|
||||||
|
|
||||||
def send_thinking_note(self):
|
|
||||||
data = {
|
|
||||||
"chat_id" : self.chat_id,
|
|
||||||
"action" : "typing",
|
|
||||||
}
|
|
||||||
send_url = self.base_url + "sendChatAction"
|
|
||||||
try:
|
|
||||||
r = requests.post(send_url, data=data)
|
|
||||||
except:
|
|
||||||
print("Could not show that I'm thinking =(")
|
|
||||||
|
|
||||||
|
|
||||||
def send_message(self, message):
|
|
||||||
print("SENDING: " + emoji.demojize(message))
|
|
||||||
|
|
||||||
data = {
|
|
||||||
'chat_id': self.chat_id,
|
|
||||||
'text': emoji.emojize(message),
|
|
||||||
"parse_mode": "HTML",
|
|
||||||
"reply_to_message_id" : self.message_id,
|
|
||||||
}
|
|
||||||
send_url = self.base_url + "sendMessage"
|
|
||||||
try:
|
|
||||||
r = requests.post(send_url, data=data)
|
|
||||||
except:
|
|
||||||
log = self.persistence.read("log")
|
|
||||||
log.append(str(datetime.datetime.now()) + " - did not send:\n" + message)
|
|
||||||
self.persistence.write("log", log)
|
|
||||||
message_sent = self.persistence.read("message_sent")
|
|
||||||
self.persistence.write("message_sent", message_sent + 1)
|
|
||||||
|
|
||||||
|
|
||||||
def emojify_word(self,word):
|
def emojify_word(self,word):
|
||||||
""""""
|
""""""
|
||||||
string_emoji = ""
|
string_emoji = ""
|
||||||
@ -240,7 +120,7 @@ class ChatBot():
|
|||||||
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. At tellus at urna condimentum mattis pellentesque id nibh. Convallis aenean et tortor at risus viverra adipiscing at in. Aliquet risus feugiat in ante metus dictum. Tincidunt augue interdum velit euismod in pellentesque massa placerat duis. Tincidunt vitae semper quis lectus nulla at. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt. Gravida rutrum quisque non tellus orci. Adipiscing at in tellus integer feugiat. Integer quis auctor elit sed vulputate mi sit amet mauris. Risus pretium quam vulputate dignissim suspendisse in est. Cras fermentum odio eu feugiat pretium. Ut etiam sit amet nisl purus in mollis nunc sed. Elementum tempus egestas sed sed risus pretium quam. Massa ultricies mi quis hendrerit dolor magna eget."
|
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. At tellus at urna condimentum mattis pellentesque id nibh. Convallis aenean et tortor at risus viverra adipiscing at in. Aliquet risus feugiat in ante metus dictum. Tincidunt augue interdum velit euismod in pellentesque massa placerat duis. Tincidunt vitae semper quis lectus nulla at. Quam nulla porttitor massa id neque aliquam vestibulum morbi blandit. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt. Gravida rutrum quisque non tellus orci. Adipiscing at in tellus integer feugiat. Integer quis auctor elit sed vulputate mi sit amet mauris. Risus pretium quam vulputate dignissim suspendisse in est. Cras fermentum odio eu feugiat pretium. Ut etiam sit amet nisl purus in mollis nunc sed. Elementum tempus egestas sed sed risus pretium quam. Massa ultricies mi quis hendrerit dolor magna eget."
|
||||||
else:
|
else:
|
||||||
message = "Lorem ipsum dolor sit amet, bla bla bla..."
|
message = "Lorem ipsum dolor sit amet, bla bla bla..."
|
||||||
self.send_message(message)
|
self.telegram.send_message(message)
|
||||||
|
|
||||||
|
|
||||||
def bot_print_status(self, params):
|
def bot_print_status(self, params):
|
||||||
@ -251,9 +131,10 @@ class ChatBot():
|
|||||||
message += "Uptime: " + delta[:delta.rfind(".")] + "\n"
|
message += "Uptime: " + delta[:delta.rfind(".")] + "\n"
|
||||||
message += "Reboots: " + str(self.persistence.read("reboots")) + "\n"
|
message += "Reboots: " + str(self.persistence.read("reboots")) + "\n"
|
||||||
message += "IP-Adress: " + ip + "\n"
|
message += "IP-Adress: " + ip + "\n"
|
||||||
message += "Messages read: " + str(self.persistence.read("message_read")) + "\n"
|
message += "Messages read: " + str(self.persistence.read("messages_read")) + "\n"
|
||||||
message += "Messages sent: " + str(self.persistence.read("message_sent")) + "</pre>"
|
message += "Messages sent: " + str(self.persistence.read("messages_sent")) + "\n"
|
||||||
self.send_message(message)
|
message += "Commands executed " + str(self.persistence.read("commands_executed")) + "</pre>"
|
||||||
|
self.telegram.send_message(message)
|
||||||
if "full" in params:
|
if "full" in params:
|
||||||
self.bot_print_log([])
|
self.bot_print_log([])
|
||||||
|
|
||||||
@ -261,56 +142,28 @@ class ChatBot():
|
|||||||
def bot_show_weather(self, params):
|
def bot_show_weather(self, params):
|
||||||
"""Shows a weather-forecast for a given location"""
|
"""Shows a weather-forecast for a given location"""
|
||||||
if len(params) != 1:
|
if len(params) != 1:
|
||||||
self.send_message("Invalid Syntax, please give one parameter, the location")
|
self.telegram.send_message("Invalid Syntax, please give one parameter, the location")
|
||||||
return
|
return
|
||||||
|
|
||||||
locations = {"freiburg": [47.9990, 7.8421], "zurich": [47.3769, 8.5417], "mulhouse": [47.7508, 7.3359]}
|
locations = {"freiburg": [47.9990, 7.8421], "zurich": [47.3769, 8.5417], "mulhouse": [47.7508, 7.3359]}
|
||||||
if params[0].lower().replace("ü","u") in locations:
|
if params[0].lower().replace("ü","u") in locations:
|
||||||
city = locations[params[0].lower().replace("ü","u")]
|
city = locations[params[0].lower().replace("ü","u")]
|
||||||
else:
|
else:
|
||||||
self.send_message("Couldn't find city, it might be added later though.")
|
self.telegram.send_message("Couldn't find city, it might be added later though.")
|
||||||
return
|
|
||||||
url = "https://api.openweathermap.org/data/2.5/onecall?"
|
|
||||||
data = {"lat" : city[0], "lon" : city[1], "exclude" : "minutely,hourly", "appid" : key.weather_api, "units" : "metric"}
|
|
||||||
|
|
||||||
try:
|
|
||||||
weather = requests.get(url,params=data).json()
|
|
||||||
except:
|
|
||||||
self.send_message("Query failed, it's my fault, I'm sorry :sad:")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
categories = {"Clouds": ":cloud:", "Rain": ":cloud_with_rain:", "Thunderstorm": "thunder_cloud_rain", "Drizzle": ":droplet:", "Snow": ":cloud_snow:", "Clear": ":sun:", "Mist": "Mist", "Smoke": "Smoke", "Haze": "Haze", "Dust": "Dust", "Fog": "Fog", "Sand": "Sand", "Dust": "Dust", "Ash": "Ash", "Squall": "Squall", "Tornado": "Tornado",}
|
message = weather.show_weather(city)
|
||||||
now = weather["current"]
|
|
||||||
message = "<b>Now:</b> " + categories[now["weather"][0]["main"]] + "\n"
|
|
||||||
message += ":thermometer: " + str(int(now["temp"])) + "°\n\n"
|
|
||||||
for i, day in enumerate(weather["daily"]):
|
|
||||||
message += "<b>+" + str(i+1) + ":</b> " + categories[day["weather"][0]["main"]] + "\n"
|
|
||||||
message += ":thermometer: :fast_down_button: " + str(int(day["temp"]["min"])) + "° , :thermometer: :fast_up_button: " + str(int(day["temp"]["max"])) + "°\n\n"
|
|
||||||
|
|
||||||
self.send_message(message)
|
self.telegram.send_message(message)
|
||||||
|
|
||||||
|
|
||||||
def bot_google_search(self, params):
|
def bot_google_search(self, params):
|
||||||
"""Does a google search and shows relevant links"""
|
"""Does a google search and shows relevant links"""
|
||||||
if len(params) < 1:
|
if len(params) < 1:
|
||||||
self.send_message("Please tell me what to look for")
|
self.telegram.send_message("Please tell me what to look for")
|
||||||
return
|
return
|
||||||
|
send_string = google.query(params)
|
||||||
param_string = ""
|
self.telegram.send_message(send_string)
|
||||||
for word in params:
|
|
||||||
param_string += word + "+"
|
|
||||||
param_string = param_string[:-1]
|
|
||||||
search_url = "https://google.com/search?q=" + param_string
|
|
||||||
|
|
||||||
try:
|
|
||||||
res = googlesearch.search(param_string.replace("+"," ") ,num=5,start=0,stop=5)
|
|
||||||
send_string = "Google search for <b>" + param_string.replace("+"," ") + "</b>:\n"
|
|
||||||
for url in res:
|
|
||||||
send_string += url + "\n\n"
|
|
||||||
send_string += "Search url:\n" + search_url
|
|
||||||
except:
|
|
||||||
send_string = "Search url:\n" + search_url
|
|
||||||
self.send_message(send_string)
|
|
||||||
|
|
||||||
|
|
||||||
def bot_print_events(self, params):
|
def bot_print_events(self, params):
|
||||||
@ -330,14 +183,14 @@ class ChatBot():
|
|||||||
delta += datetime.timedelta(days = 365)
|
delta += datetime.timedelta(days = 365)
|
||||||
send_string += key + ": " + str(delta.days) + " days \n"
|
send_string += key + ": " + str(delta.days) + " days \n"
|
||||||
|
|
||||||
self.send_message(send_string)
|
self.telegram.send_message(send_string)
|
||||||
|
|
||||||
|
|
||||||
def bot_emojify(self, params):
|
def bot_emojify(self, params):
|
||||||
"""Converts a string to emojis"""
|
"""Converts a string to emojis"""
|
||||||
|
|
||||||
if len(params) < 2:
|
if len(params) < 2:
|
||||||
self.send_message(emoji.emojize("Please send a separator as the first argument, and the text afterwards.\nExample:\n/emojify :heart: Example text"))
|
self.telegram.send_message(emoji.emojize("Please send a separator as the first argument, and the text afterwards.\nExample:\n/emojify :heart: Example text"))
|
||||||
|
|
||||||
sep = params[0]
|
sep = params[0]
|
||||||
string_emoji = ""
|
string_emoji = ""
|
||||||
@ -345,7 +198,7 @@ class ChatBot():
|
|||||||
out_string = self.emojify_word(word)
|
out_string = self.emojify_word(word)
|
||||||
string_emoji += out_string + sep
|
string_emoji += out_string + sep
|
||||||
|
|
||||||
self.send_message(string_emoji)
|
self.telegram.send_message(string_emoji)
|
||||||
|
|
||||||
|
|
||||||
def bot_show_help(self, params):
|
def bot_show_help(self, params):
|
||||||
@ -356,27 +209,27 @@ class ChatBot():
|
|||||||
for entry in entries:
|
for entry in entries:
|
||||||
send_text += "<b>" + entry + "</b> - "
|
send_text += "<b>" + entry + "</b> - "
|
||||||
send_text += "<code>" + self.commands[entry].__doc__ + "</code>\n\n"
|
send_text += "<code>" + self.commands[entry].__doc__ + "</code>\n\n"
|
||||||
self.send_message(send_text)
|
self.telegram.send_message(send_text)
|
||||||
|
|
||||||
|
|
||||||
def bot_print_log(self, params):
|
def bot_print_log(self, params):
|
||||||
"""Shows an error-log, mostly of bad api-requests"""
|
"""Shows an error-log, mostly of bad api-requests"""
|
||||||
if "clear" in params:
|
if "clear" in params:
|
||||||
self.persistence.write("log",[])
|
self.persistence.write("log",[])
|
||||||
self.send_message("Log cleared")
|
self.telegram.send_message("Log cleared")
|
||||||
return
|
return
|
||||||
send_text = ""
|
send_text = ""
|
||||||
for event in self.persistence.read("log"):
|
for event in self.persistence.read("log"):
|
||||||
send_text += event + "\n"
|
send_text += event + "\n"
|
||||||
if send_text == "":
|
if send_text == "":
|
||||||
send_text += "No errors up to now"
|
send_text += "No errors up to now"
|
||||||
self.send_message(send_text)
|
self.telegram.send_message(send_text)
|
||||||
|
|
||||||
|
|
||||||
def bot_show_wikipedia(self, params):
|
def bot_show_wikipedia(self, params):
|
||||||
"""Shows the wikipedia entry for a given therm"""
|
"""Shows the wikipedia entry for a given therm"""
|
||||||
if len(params) > 2 or len(params) == 0:
|
if len(params) > 2 or len(params) == 0:
|
||||||
self.send_message("Please only search for one word at a time. 1rst param is for language (de or fr or en or ...)")
|
self.telegram.send_message("Please only search for one word at a time. 1rst param is for language (de or fr or en or ...)")
|
||||||
return
|
return
|
||||||
|
|
||||||
if len(params) == 2:
|
if len(params) == 2:
|
||||||
@ -390,9 +243,9 @@ class ChatBot():
|
|||||||
url = "https://en.wikipedia.org/wiki/" + params[0]
|
url = "https://en.wikipedia.org/wiki/" + params[0]
|
||||||
r = requests.get(url)
|
r = requests.get(url)
|
||||||
if r.status_code == 404:
|
if r.status_code == 404:
|
||||||
self.send_message("No result found for query")
|
self.telegram.send_message("No result found for query")
|
||||||
return
|
return
|
||||||
self.send_message(url)
|
self.telegram.send_message(url)
|
||||||
|
|
||||||
|
|
||||||
def bot_do_all(self,params):
|
def bot_do_all(self,params):
|
||||||
@ -402,11 +255,10 @@ class ChatBot():
|
|||||||
self.commands[command](["en","Freiburg"])
|
self.commands[command](["en","Freiburg"])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def bot_zvv(self,params):
|
def bot_zvv(self,params):
|
||||||
"""Uses the swiss travel api to return the best route between a start- and endpoint in Zurich (actually whole Switzerland, but I haven't tested that)"""
|
"""Uses the swiss travel api to return the best route between a start- and endpoint in Zurich (actually whole Switzerland, but I haven't tested that)"""
|
||||||
if len(params) != 2:
|
if len(params) != 2:
|
||||||
self.send_message("Please give me your start and endpoint")
|
self.telegram.send_message("Please give me your start and endpoint")
|
||||||
return
|
return
|
||||||
|
|
||||||
url = "http://transport.opendata.ch/v1/connections"
|
url = "http://transport.opendata.ch/v1/connections"
|
||||||
@ -431,17 +283,32 @@ class ChatBot():
|
|||||||
else:
|
else:
|
||||||
text += "Walk."
|
text += "Walk."
|
||||||
text += "\n"
|
text += "\n"
|
||||||
self.send_message(text)
|
self.telegram.send_message(text)
|
||||||
except:
|
except:
|
||||||
self.send_message("Invalid api call.")
|
self.telegram.send_message("Invalid api call.")
|
||||||
|
|
||||||
|
|
||||||
def bot_cronjob(self, params):
|
def bot_cronjob(self, params):
|
||||||
"""Allows you to add a timed command, in a crontab-like syntax. Not implemented yet.
|
"""Allows you to add a timed command, in a crontab-like syntax. Not implemented yet.
|
||||||
Example usage: /cronjob add 0 8 * * * weather Zürich
|
Example usage: /cronjob add 0 8 * * * weather Zürich
|
||||||
"""
|
"""
|
||||||
self.send_message("I'm not functional yet. But when I am, it is gonna be legendary!")
|
self.telegram.send_message("I'm not functional yet. But when I am, it is gonna be legendary!")
|
||||||
|
|
||||||
|
|
||||||
|
def bot_tell_joke(self, params):
|
||||||
|
"""Tells you the top joke on r/jokes"""
|
||||||
|
joke = reddit.get_top_text("jokes",3)
|
||||||
|
self.telegram.send_message(joke)
|
||||||
|
|
||||||
|
|
||||||
|
def bot_send_meme(self, params):
|
||||||
|
"""Sends a meme from r/memes"""
|
||||||
|
urls = reddit.get_top_image("memes",3)
|
||||||
|
for u in urls:
|
||||||
|
try:
|
||||||
|
self.telegram.send_photo(u["image"], u["caption"])
|
||||||
|
except:
|
||||||
|
self.telegram.send_message("Meme won't yeet")
|
||||||
|
|
||||||
#######################################################################
|
#######################################################################
|
||||||
bot = ChatBot("ChatterBot", version="1.03")
|
bot = ChatBot("ChatterBot", version="1.03")
|
||||||
|
@ -1 +0,0 @@
|
|||||||
{"message_read": 27, "message_sent": 17, "log": [], "chat_members": {"364520272": "Remy Moll"}, "reboots": 20}
|
|
1
persistence/__init__.py
Normal file
1
persistence/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Placeholder
|
1
persistence/permanent_vars.json
Normal file
1
persistence/permanent_vars.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages_read": 56, "messages_sent": 34, "commands_executed": 21, "photos_sent": 4, "log": [], "chat_members": {"364520272": "Remy Moll"}, "reboots": 49}
|
@ -1,7 +1,7 @@
|
|||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
|
|
||||||
class PersistentVars():
|
class Variables():
|
||||||
""""""
|
""""""
|
||||||
|
|
||||||
def __init__(self,savefile_path):
|
def __init__(self,savefile_path):
|
||||||
@ -26,7 +26,6 @@ class PersistentVars():
|
|||||||
print("Config not written - critical")
|
print("Config not written - critical")
|
||||||
|
|
||||||
def read(self, name=""):
|
def read(self, name=""):
|
||||||
|
|
||||||
if self.last_action == "read":
|
if self.last_action == "read":
|
||||||
vars = self.savefile
|
vars = self.savefile
|
||||||
else:
|
else:
|
||||||
@ -43,3 +42,18 @@ class PersistentVars():
|
|||||||
vars = vars[name]
|
vars = vars[name]
|
||||||
|
|
||||||
return vars
|
return vars
|
||||||
|
|
||||||
|
def increment(self, name=""):
|
||||||
|
if self.last_action == "read":
|
||||||
|
pre = self.savefile
|
||||||
|
else:
|
||||||
|
pre = self.read()
|
||||||
|
|
||||||
|
try:
|
||||||
|
pre[name] += 1
|
||||||
|
file = open(self.path,"w")
|
||||||
|
json.dump(pre, file)
|
||||||
|
file.close()
|
||||||
|
self.last_action = "write"
|
||||||
|
except:
|
||||||
|
print("Config not written - critical")
|
Loading…
x
Reference in New Issue
Block a user