far better structure, more modular
This commit is contained in:
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
|
Reference in New Issue
Block a user