Skip to content

Commit cc4800b

Browse files
stuff
1 parent 3bacd82 commit cc4800b

File tree

10 files changed

+999
-16
lines changed

10 files changed

+999
-16
lines changed

anime.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#! /usr/bin/python3
2+
3+
# by FvH, released under Apache License v2.0
4+
5+
# either install 'python3-paho-mqtt' or 'pip3 install paho-mqtt'
6+
7+
import paho.mqtt.client as mqtt
8+
import requests
9+
import threading
10+
import time
11+
12+
mqtt_server = 'mqtt.vm.nurd.space' # TODO: hostname of MQTT server
13+
topic_prefix = 'GHBot/' # leave this as is
14+
channels = ['nurdbottest', 'nurds', 'nurdsbofh'] # TODO: channels to respond to
15+
prefix = '!' # !command, will be updated by ghbot
16+
17+
def announce_commands(client):
18+
target_topic = f'{topic_prefix}to/bot/register'
19+
20+
client.publish(target_topic, 'cmd=qanime|descr=Anime quotes')
21+
22+
def get_json(url):
23+
r = requests.get(url)
24+
25+
return r.json()
26+
27+
def on_message(client, userdata, message):
28+
global prefix
29+
30+
text = message.payload.decode('utf-8')
31+
32+
topic = message.topic[len(topic_prefix):]
33+
34+
if topic == 'from/bot/command' and text == 'register':
35+
announce_commands(client)
36+
37+
return
38+
39+
if topic == 'from/bot/parameter/prefix':
40+
prefix = text
41+
42+
return
43+
44+
if len(text) == 0:
45+
return
46+
47+
parts = topic.split('/')
48+
channel = parts[2] if len(parts) >= 3 else 'nurds' # default channel if can't be deduced
49+
nick = parts[3] if len(parts) >= 4 else 'jemoeder' # default nick if it can't be deduced
50+
51+
if text[0] != prefix:
52+
return
53+
54+
command = text[1:].split(' ')[0]
55+
56+
if channel in channels or (len(channel) >= 1 and channel[0] == '\\'):
57+
response_topic = f'{topic_prefix}to/irc/{channel}/privmsg'
58+
59+
if command == 'qanime':
60+
try:
61+
j = get_json('https://animechan.vercel.app/api/random')
62+
63+
fact = j['anime']
64+
65+
client.publish(response_topic, fact)
66+
67+
except Exception as e:
68+
client.publish(response_topic, f'Exception during "qanime": {e}, line number: {e.__traceback__.tb_lineno}')
69+
70+
def on_connect(client, userdata, flags, rc):
71+
client.subscribe(f'{topic_prefix}from/irc/#')
72+
73+
client.subscribe(f'{topic_prefix}from/bot/command')
74+
75+
def announce_thread(client):
76+
while True:
77+
try:
78+
announce_commands(client)
79+
80+
time.sleep(4.1)
81+
82+
except Exception as e:
83+
print(f'Failed to announce: {e}')
84+
85+
client = mqtt.Client(sys.argv[0], clean_session=False)
86+
client.on_message = on_message
87+
client.on_connect = on_connect
88+
client.connect(mqtt_server, port=1883, keepalive=4, bind_address="")
89+
90+
t = threading.Thread(target=announce_thread, args=(client,))
91+
t.start()
92+
93+
client.loop_forever()

0 commit comments

Comments
 (0)