简体   繁体   English

如何修复我的 ctx 不工作(Python 中的 Discord Bot)?

[英]How do I fix my ctx not working (Discord Bot in Python)?

So I just started trying to make a discord bot for my school Coding Server.所以我刚开始尝试为我的学校编码服务器制作一个 discord 机器人。 I got the hello command to work when the user says ",hello".当用户说“,你好”时,我得到了 hello 命令工作。 and the bot then says "Hello @user" back, I was trying to code a command that when the user types in ",codehelp".然后机器人说“你好@user”,我试图编写一个命令,当用户输入“,codehelp”时。 the bot tags the Intermediate and Advanced roles on our server, but some stuff stopped working.机器人在我们的服务器上标记了中级和高级角色,但有些东西停止了工作。

This is the code:这是代码:

import discord
from asyncio import *

TOKEN = 'my_token'

Intermediate = discord.utils.get(ctx.guild.roles, id=the_role_id)

client = discord.Client()

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await message.channel.send(msg)

    if message.content.startswith('!codehelp'):
        msg = '{Intermediate.mention} {0.author.mention} needs help with his code!'.format(message)
        await message.channel.send(msg)


@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(TOKEN)

I've managed to narrow down the NameError to one place: the ctx.guild.roles part.我设法将 NameError 缩小到一个地方: ctx.guild.roles部分。

It says the following:它说:

Traceback (most recent call last):
  File "C:/Users/lenovo/PycharmProjects/untitled/Discord Bot Pathways", line 6, in <module>
    Intermediate = discord.utils.get(ctx.guild.roles, id=the_role_id)
NameError: name 'ctx' is not defined

I'm a complete beginner at Discord Bot programming while I have some experience in Python so help would be much appreciated.我是 Discord Bot 编程的完整初学者,而我在 Python 方面有一些经验,因此将不胜感激。

Also here is my software:这也是我的软件:

  • Windows 10 Windows 10
  • discord.py 1.0+ discord.py 1.0+
  • Python v3.8.3 Python v3.8.3
  • PyCharm IDE PyCharm IDE

You need to get guild with id and get roles.您需要获得带有 id 的公会并获得角色。 Paste this line after client =... :client =...之后粘贴此行:

Intermediate = discord.utils.get(client.get_guild(GUILD_ID).roles, id=the_role_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM