如何加入服务器?

2024-05-18 21:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python设置一个不和谐的机器人。我有一个预先存在的不和谐服务器,我希望机器人加入,但我很难这样做。

import discord
import asyncio
import logging

logging.basicConfig(level=logging.INFO)

client = discord.Client()

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


@client.event
async def on_message(message):
    print(message)
    if message.content.startswith('!test'):
        counter = 0
        tmp = await client.send_message(message.channel, 'Calculating messages...')
        async for log in client.logs_from(message.channel, limit=100):
            if log.author == message.author:
                counter += 1

        await client.edit_message(tmp, 'You have {} messages.'.format(counter))
    elif message.content.startswith('!sleep'):
        await asyncio.sleep(5)
        await client.send_message(message.channel, 'Done sleeping')

client.run('token')

这实际上是GitHub页面上给出的基本discord.py脚本。然而,我似乎不知道如何让它真正加入我的服务器。将此行插入on_ready函数时:

server = await client.accept_invite('instant-invite-code')

使用“即时邀请代码”替换为实际的即时邀请代码(我尝试了discord.gg/code和code),我得到

discord.errors.Forbidden: FORBIDDEN (status code: 403): Bots cannot use this endpoint

日志记录确实有效;我用用户名和id获得输出。我的bot用discord API注册,我已经有了一个令牌。


Tags: import服务器clientasynciomessageasynconlogging
2条回答

我建议编辑如下代码:

    @client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('Invite: https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(client.user.id))
    print('------')

我认为这是最好最简单的解决办法。对我有用。

EDIT:Discord实际上生成了自己的OAuth2 url生成器,因此使用该生成器:https://discordapp.com/developers/tools/oauth2-url-generator

我也遇到了一些麻烦。你需要做的是:

  1. 转到Discord developer pages(如果没有,请登录)。
  2. 转到要添加到频道的机器人的应用程序。
  3. 复制客户机/应用程序ID
  4. 转到https://discordapp.com/oauth2/authorize?client_id=CLIENT_ID_GOES_HERE&scope=bot&permissions=0<;您可以在此处设置bot的权限。Permissions can be calculated here
  5. 选择“服务器”,然后单击“授权”。

您的机器人现在将是服务器的成员,并将响应您给它的命令。例如!在您给出的代码中进行测试。

编辑:现在可以使用权限链接(1)生成所需的整个URL。

相关问题 更多 >

    热门问题