带有sqlite经济学的Discord机器人

哈Ha!


我想分享自己的经验,因为我写了一篇经济实用的机器人,使用sqlite和其他小东西开发了一个不和谐的服务器。

准备阶段


机器人创造


因此,在编写机器人之前,我们需要创建它并获得令牌:

  1. 转到开发者站点
  2. 点击“新应用”按钮并命名该机器人
  3. 通过登录机器人并在“设置”列表中找到“机器人”选项卡来获取机器人令牌。

所需模块


毕竟,我们是用python而不是ASM编写的,所以我们将需要一些模块

$ pip install discord.py # api     

 $ pip install tabulate #     

写作阶段


导入模块


导入模块就像用HTML + CSS编写单个页面一样简单。

 import sqlite3 # sqlite import discord # discord api from discord.ext import commands #     from tabulate import tabulate #     import json #    ,        

连接到sqlite


这里没有什么复杂的。 导入后,编写以下内容:

 conn = sqlite3.connect("Discord.db") #  :memory: cursor = conn.cursor() 

数据库准备


数据库中将有2个shop和users表。

 CREATE TABLE "shop" ( "id" INT, "type" TEXT, "name" TEXT, "cost" INT ) 

 CREATE TABLE "users" ( "id" INT, "nickname" TEXT, "mention" TEXT, "money" INT, "rep_rank" TEXT, "inventory" TEXT, "lvl" INT, "xp" INT ) 

准备编写机器人逻辑


创建bot变量。

 bot = commands.Bot(command_prefix="_")#  command_prefix    , , ,   .. 

在所有代码的结尾,我们编写了一个启动机器人的方法。

 bot.run(" ,       ") 

现在,让我们开始编写我们的机器人。

 bot = commands.Bot(command_prefix="_") #     bot.run(" ,       ") 

接下来,我们编写on_ready()事件,该事件负责机器人的可用性。

 @bot.event async def on_ready(): print("Bot Has been runned")#   for guild in bot.guilds:#..    ,       print(guild.id)# id  serv=guild#    for member in guild.members:#,    cursor.execute(f"SELECT id FROM users where id={member.id}")#,      if cursor.fetchone()==None:#   cursor.execute(f"INSERT INTO users VALUES ({member.id}, '{member.name}', '<@{member.id}>', 50000, 'S','[]',0,0)")#       else:#  pass conn.commit()#    

之后,为了不再次启动bot,请编写on_member_join()方法

 @bot.event async def on_member_join(member): cursor.execute(f"SELECT id FROM users where id={member.id}")# ,      if cursor.fetchone()==None:#   cursor.execute(f"INSERT INTO users VALUES ({member.id}, '{member.name}', '<@{member.id}>', 50000, 'S','[]',0,0)")#       else:#  pass conn.commit()#    

如果我们的机器人是经济的,则必须有一种货币,其收入和支出。 可以使用体验系统安排收入。

 @bot.event async def on_message(message): if len(message.content) > 10:#    > 10 ... for row in cursor.execute(f"SELECT xp,lvl,money FROM users where id={message.author.id}"): expi=row[0]+random.randint(5, 40)#     cursor.execute(f'UPDATE users SET xp={expi} where id={message.author.id}') lvch=expi/(row[1]*1000) print(int(lvch)) lv=int(lvch) if row[1] < lv:#    ,     ,... await message.channel.send(f' !')#  ... bal=1000*lv cursor.execute(f'UPDATE users SET lvl={lv},money={bal} where id={message.author.id}')#    await bot.process_commands(message)#     ctx  conn.commit()#    

我们写了主要部分之一。 仍然需要编写诸如帐户,商店等命令。 我更直观地认为。

 @bot.command() async def account(ctx): # _account ( "_",     ) table=[["nickname","money","lvl","xp"]] for row in cursor.execute(f"SELECT nickname,money,lvl,xp FROM users where id={ctx.author.id}"): table.append([row[0],row[1],row[2],row[3]]) await ctx.send(f">\n{tabulate(table)}") @bot.command() async def inventory(ctx):# _inventory ( "_",     ) counter=0 for row in cursor.execute(f"SELECT inventory FROM users where id={ctx.author.id}"): data=json.loads(row[0]) table=[["id","type","name"]] for row in data: prt=row for row in cursor.execute(f"SELECT id,type,name FROM shop where id={prt}"): counter+=1 table.append([row[0],row[1],row[2]]) if counter==len(data): await ctx.send(f'>\n{tabulate(table)}') @bot.command() async def shop(ctx):# _shop ( "_",     ) counter=0 table=[["id","type","name","cost"]] for row in cursor.execute(f"SELECT id,type,name,cost FROM shop"): counter+=1 table.append([row[0],row[1],row[2],row[3]]) if counter==4: await ctx.send(f'>\n{tabulate(table)}') 

如果您有商店,那么您可以购买? 是不是

 async def buy(ctx, a: int): uid=ctx.author.id await ctx.send('...    ,   id  [buy {id}]') for row in cursor.execute(f"SELECT money FROM users where id={uid}"): money = row[0] for row in cursor.execute(f"SELECT id,name,cost FROM shop where id={a}"): cost=row[2] if money >= cost:#    ,... money -=cost await ctx.send(f'  "{row[1]}"  {row[2]}') for row in cursor.execute(f"SELECT inventory FROM users where id={uid}"): data=json.loads(row[0]) data.append(a) daed=json.dumps(data) cursor.execute('UPDATE users SET money=?,inventory = ? where id=?',(money,daed,uid))#     pass if money < cost:#    await ctx.send(f' ') pass conn.commit()#    

结论


在这里,我们有一个简单的机器人。 希望这对某人有帮助。

我知道有可能(必要)向其中添加很多功能和芯片,但这是代码的裸露版本,初学者可以使用它来理解discord.py,sqlite模块和python内置方法的工作方式。

谢谢大家的关注。 到连接!

Source: https://habr.com/ru/post/zh-CN482290/


All Articles