nerve/main.py

93 lines
2.6 KiB
Python
Raw Normal View History

2022-02-23 02:45:33 -05:00
import json
import nio
import simplematrixbotlib as botlib
2022-03-03 14:18:07 -05:00
import commands
2022-02-23 02:45:33 -05:00
2022-05-18 03:59:32 -04:00
#TODO move state functionality entirely to features.py
2022-02-23 02:45:33 -05:00
data = json.loads(open('data.json').read())
dfaq = data["faq"]
2022-03-07 04:24:40 -05:00
userstate = data['users']
2022-02-23 02:45:33 -05:00
faq_text = dfaq["header"] + "".join(["\n"+q["question"]+"\n"+q["answer"]
for q in dfaq["questions"]]) + "\n\n"+dfaq["footer"]
creds = botlib.Creds(
data["homeserver"],
data['username'],
data['password']
)
bot = botlib.Bot(creds)
PREFIX = '!'
def load_faq():
dfaq = json.loads(open('data.json').read())["faq"]
return dfaq["header"] + "".join(["\n"+q["question"]+"\n"+q["answer"] for q in dfaq["questions"]]) + "\n\n"+dfaq["footer"]
2022-03-07 04:24:40 -05:00
def save_userstate():
with open('data.json','w') as f:
f.write(json.dumps(data,indent=4))
2022-02-23 02:45:33 -05:00
@bot.listener.on_message_event
async def faq(room, message):
2022-03-07 04:24:40 -05:00
if message.sender not in userstate:
userstate[message.sender] = {"state":[]}
save_userstate()
state = userstate[message.sender]['state']
2022-05-18 03:59:32 -04:00
result = commands.handle_command(state,message.sender,message.body)
2022-03-07 04:24:40 -05:00
if result['response']!= None:
state = result['state']
userstate[message.sender]['state'] = result['state']
save_userstate()
await bot.api.send_markdown_message(
room.room_id,
result['response']
)
2022-02-23 02:45:33 -05:00
match = botlib.MessageMatch(room, message, bot, PREFIX)
2022-03-07 04:24:40 -05:00
#print(f"{message.sender} : {message.body}")
2022-02-23 02:45:33 -05:00
if match.is_not_from_this_bot() and match.prefix() and match.command(
"faq"):
await bot.api.send_markdown_message(
room.room_id,
load_faq())
2022-03-07 04:24:40 -05:00
2022-02-23 02:45:33 -05:00
@bot.listener.on_custom_event(nio.InviteMemberEvent)
2022-02-23 03:47:03 -05:00
async def example(room, event):
2022-02-23 02:45:33 -05:00
if event.membership == "join":
await bot.api.send_markdown_message(
room.room_id,
load_faq()
)
def get_questions():
return json.loads(open('data.json').read())["faq"]["questions"]
@bot.listener.on_message_event
async def faqresponse(room, message):
match = botlib.MessageMatch(room, message, bot, PREFIX)
if match.is_not_from_this_bot():
response = ""
questions = get_questions()
for q in questions:
if sum([ 1 for kp in q["key_phrases"] if kp in message.body]) == len(q["key_phrases"]):
2022-02-23 03:47:03 -05:00
response += q["question"] + "\n" + q["answer"]+"\n"
2022-02-23 02:45:33 -05:00
if response != "":
await bot.api.send_markdown_message(
room.room_id,
2022-02-23 03:47:03 -05:00
response + dfaq["footer"]
2022-02-23 02:45:33 -05:00
)
2022-03-03 14:18:07 -05:00
2022-02-23 03:47:03 -05:00
2022-02-23 02:45:33 -05:00
bot.run()