【问题标题】:Im learning to make a bot using python. What do I do so that I can create a new channel using the commands?我正在学习使用 python 制作机器人。我该怎么做才能使用命令创建新频道?
【发布时间】:2021-07-22 20:06:42
【问题描述】:

感谢之前帮助我回答最后一个问题的人 我想要做的是为一个函数创建一个不同的文件,当你输入“!创建”+(我希望频道的名称)时,它会创建一个具有指定名称的新频道,我希望该文件能够在主频道回调

代码 1:

import os
import discord
import createchannel

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

commands = {
    '$Hello' : 'Hello! write "$Help" to find more about the CazB0T ',
    '$Help' : 'Hi again! The CazB0T is still in beta stages...the only 5 commands are $Hello, $Help, $Test1, $Test2, and $Test3',
    '$Test1' : 'This is Test1',
    '$Test2' : 'This is Test2',
    '$Test3' : 'This is Test3'
}

createchannel()

my_secret = os.environ['token']

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

    for key, value in commands.items():
        if message.content.startswith(key):
            await message.channel.send(value)



client.run(os.getenv('token'))

代码 2:

import discord
import os
client = discord.Client()
@client.event
async def on_chancreate(channel):
  channelname = input()
  if channel.content == "!create" + channelname:
    channel = await channel.create_text_channel(channelname)

client.run(os.getenv('token'))

【问题讨论】:

  • 1.我建议为每个命令使用单独的函数 - 可以使用适当的装饰器 - 而不是听每条消息。 2. 即使你在 on_message 中处理它们,这也不是搜索 dict 的最佳方式——你是线性的,O(n),而 dict 键可以在 O(1) 中搜索。 3. Bot 无法处理input - 这是控制台功能。 4. "!create" + channelname 之间不会有空格。
  • 如何使用命令创建具有指定名称的新频道?

标签: python discord bots e


【解决方案1】:

在 cmets 中,我假设您想通过命令创建通道。为此,您需要考虑以下几点:

如果您想使用commands,您必须将client = discord.Client() 更改为client = commands.Bot(command_prefix="YourPrefix") 并从discord.ext 导入commands

from discord.ext import commands

client = commands.Bot(command_prefix="!") # Example prefix

首先:您必须设置必须满足的条件。您希望能够给频道起自己的名字吗?假设这是必需的参数:

@client.command()
async def cchannel(ctx, *, name):
  • 我们说过name 是必需的参数。
  • 使用* 以便我们还可以输入t e s t 之类的名称,而不仅仅是test

第二:您需要定义要在其中创建频道的公会。为此,我们使用:

guild = ctx.message.guild

最后我们想create a text channel为此,我们使用:

@client.command()
async def channel(ctx, *, name):
    guild = ctx.message.guild # Get the guild
    await guild.create_text_channel(name=name) # Create a text channel based on the input
    await ctx.send(f"Created a new channel with the name `{name}`") # Optional
  • 在创建频道时,我们说名称应该是我们必需的参数name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 2021-09-05
    • 2022-01-10
    相关资源
    最近更新 更多