问题描述
所以我正在制作一个不和谐机器人,它将为我服务器中的每个人记录某个“信用”,我们可以通过一个简单的命令增加或减少某些人的信用。到目前为止,我遇到的唯一问题是我不希望有人能够给自己信任。将信誉视为某人对您的尊重程度。这纯粹是个玩笑,但我和我的朋友觉得这将是一个很酷的小项目,可以磨练我们的 Python 技能。
这是我们的代码:
import discord
import os
from discord.ext import commands
from replit import
dblist = ["NMShoe#xxxx","Nathan"],["Jerlopo#xxxx","Shawn"],["Flinters#xxxx","Kaylan"] #x's are numbers
@bot.command(name="givecred",description="Gives credit to a certain person.")
async def givecred(ctx,name: str,cred: int): #takes (str)name and (int)cred into function
if ctx.author == bot.user: #if the bot reads a message from itself,it ignores
return
else:
if name in db.keys(): #checks if the name they entered is in the database
await ctx.send("Added {} cred to {}!".format(cred,name))
db[name] = db[name] + cred #adds and updates database value
await ctx.send("{}'s at {} cred Now!".format(name,db[name]))
return
else:
await ctx.send("Did not enter the correct variables. Please enter: '.givecred {name} {#of cred}'.")
return
#Database (key,value) --> <Shawn,0>,<Nathan,0> This is how I have the database set up at the moment
但我基本上需要在第一个 else 语句的开头使用 if 语句以确保如果我要说“.givecred Nathan 10”,它会认识到我正在尝试给自己信任并抛出消息而不是添加我的数据库值的信誉。问题是我不希望每个人都必须记住彼此的完整用户名,因为它涉及字符和随机的 4 个数字,并且服务器的一些成员有昵称。这就是为什么我在数据库中有我们的名字,以便我们可以将它与传递给命令的名称字符串进行比较。我尝试使用 2D 数组并让它检查我的 ctx.author,它会吐出我的“NMShoe#xxxx”,但我无法弄清楚如何在 if 语句中基本上将所有三个变量相互比较。
修正:
name_to_username = {
"Nathan": "NMShoe#xxxx","Shawn": "Jerlopo#xxxx","Kaylan": "Flinters#xxxx"}
@bot.command(name="givecred",cred: int):
if name in name_to_username:
username = name_to_username[name] #this is the answer given by the below answer THANK YOU mackorone!!!
if ctx.author == bot.user:
return
else:
if name in db.keys():
if str(ctx.author) != username: #MUST MAKE cxt.author a string for some random reason
await ctx.send("Added {} cred to {}!".format(cred,name))
db[name] = db[name] + cred
await ctx.send("{}'s at {} cred Now!".format(name,db[name]))
return
else:
await ctx.send("Can't give cred to yourself.")
return
else:
await ctx.send("Did not enter the correct variables. Please enter: '.givecred {name} {# of cred}'.")
return
解决方法
很酷的项目创意!我认为您正在寻找 dict
数据结构,它允许您定义从一个值到另一个值的映射。而不是这样:
dblist = ["NMShoe#xxxx","Nathan"],["Jerlopo#xxxx","Shawn"],["Flinters#xxxx","Kaylan"] #x's are numbers
你应该这样写:
name_to_username = {
"Nathan": "NMShoe#xxxx","Shawn": "Jerlopo#xxxx","Kaylan": "Flinters#xxxx",}
然后可以像这样检查名称是否正确:
if name in name_to_username:
username = name_to_username[name]
# ... other stuff here
这有帮助吗?