StruFu-Bot/Jan/dbtest command.py

107 lines
2.7 KiB
Python

from discord.ext import commands
import asyncio
import random
bot = commands.Bot(command_prefix="!")
class sf_user:
def __init__(self, id, username, dmchannel):
self.id = id
self.name = username
self.channel = dmchannel
self.question = 0
self.category = 0
self.semester = 0
async def initialize():
await bot.login("Nzg1MTkxODM3OTg3MzczMDg2.X80Q4g.bK_vMhhESanMOA78KxHfmJft2vk")
userfile = open("users.txt", encoding="UTF-8")
userlines = userfile.readlines()
for i in userlines:
userdata = i.split("|")
add_user = await bot.fetch_user(userdata[1])
users.append(sf_user(int(userdata[0]), add_user, await add_user.create_dm()))
userfile.close()
await bot.connect()
@bot.event
async def on_ready():
print("we logged in as {0.user.name}".format(bot))
return
@bot.command()
async def start(ctx):
print("hello")
for i in users:
if i.name == ctx.author:
await ctx.send("User already in database")
return
users.append(sf_user(len(users), ctx.author.id, await ctx.author.create_dm()))
await users[-1].channel.send("Hello")
userfile = open("users.txt", "a")
userfile.write(f"{users[-1].id}|{users[-1].name}|{users[-1].channel}\n")
userfile.close()
return
@bot.command()
async def question(ctx):
current_user = 0
for i in users:
if i.channel == ctx.channel:
current_user = i
if current_user == 0:
await ctx.send("User not in database")
return
q_id = random.randint(0, 10)
question_str = get_question(q_id)[0]
users[current_user.id].question = q_id
await current_user.channel.send(question_str)
return
def get_question(q_id):
all_lines = []
f = open("fragen_antworten.txt", encoding="UTF-8")
lines = f.readlines()
for line in lines:
all_lines.append(line.split("|"))
return all_lines[q_id][0], all_lines[q_id][1] #[q_id][0] is the question, [q_id][1] is the answer
@bot.command()
async def debug(ctx):
for i in users:
await ctx.send(f"Question:{i.question}, Name:{i.name}, Channel:{i.channel}")
return
@bot.command()
async def answer(ctx):
current_user = 0
for i in users:
if i.channel == ctx.channel:
current_user = i
if current_user == 0:
await ctx.send("User not in database")
return
answer = get_question(current_user.question)[1] # TO DO: return answer
await current_user.channel.send(answer)
return
#initialization
users = []
loop = asyncio.get_event_loop()
loop.run_until_complete(initialize())
loop.close()