在 python 中编写一个不和谐的机器人
Posted
技术标签:
【中文标题】在 python 中编写一个不和谐的机器人【英文标题】:writing a bot for discord in python 【发布时间】:2020-07-25 11:44:11 【问题描述】:我有一个有效的货币系统,但我们想要赚钱的方法。所以我想做迷你游戏,所以我做了一个掷硬币的游戏,但我不能让它工作,它告诉我当我尝试它时找不到命令。我也想做它所以游戏成本>货币所以你可以赢一点,所以基本上投注
from discord.ext import commands
import discord
import json
import random
from discord.ext.commands import Bot
from discord import Game
import time
import asyncio
bot = commands.Bot('$')
amounts =
@bot.event
async def on_ready():
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts =
@bot.command(pass_context=True)
async def balance(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have :Ereb: in the bank".format(amounts[id]))
else:
await ctx.send("You do not have an account")
@bot.command(pass_context=True)
async def register(ctx):
id = str(ctx.message.author.id)
if id not in amounts:
amounts[id] = 100
await ctx.send("You are now registered")
_save()
else:
await ctx.send("You already have an account")
@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
primary_id = str(ctx.message.author.id)
other_id = str(other.id)
if primary_id not in amounts:
await ctx.send("You do not have an account")
elif other_id not in amounts:
await ctx.send("The other party does not have an account")
elif amounts[primary_id] < amount:
await ctx.send("You cannot afford this transaction")
else:
amounts[primary_id] -= amount
amounts[other_id] += amount
await ctx.send("Transaction complete")
_save()
def _save():
with open('amounts.json', 'w+') as f:
json.dump(amounts, f)
@bot.command()
async def save():
_save()
***@bot.command() #problem
async def on_message(message):
if message.content.startswith('$coinflip'):
randomlist = ["heads","tails",]
await client.send_message(message.channel,(random.choice(randomlist)))***
bot.run("token")
```
【问题讨论】:
您遇到了什么异常或错误?错误发生在何时何地? 忽略命令中的异常无:discord.ext.commands.errors.CommandNotFound:找不到命令“coinflip” 请在帖子中提供整个错误。 这能解决您的问题吗? ***.com/questions/52900101/… 这能回答你的问题吗? Remove 'command not found' error discord.py 【参考方案1】:您需要使用bot.event
而不是bot.command
来装饰您的on_message
回调。您还需要添加bot.process_commands
行,以便正常调用其他命令。
@bot.event
async def on_message(message):
if message.content.startswith('$coinflip'):
randomlist = ["heads","tails",]
await client.send_message(message.channel,(random.choice(randomlist)))
else:
await bot.process_commands(message)
【讨论】:
我让它工作了,但它给出了两次正面或反面。以上是关于在 python 中编写一个不和谐的机器人的主要内容,如果未能解决你的问题,请参考以下文章
试图学习如何用 python 制作一个不和谐的机器人。每次我尝试启动代码时都会出现相同的错误