python3.6.1 | discord.py |以用户身份登录

时间:2017-12-17 16:11:09

标签: python-3.x python-3.6 discord discord.py

我正在尝试制作一些简单的程序,向终端显示收到的消息。现在我正在尝试询问用户登录的电子邮件和密码,但发生了一些奇怪的错误。这就是我的代码的样子:

import discord


class DiscordClient(discord.Client):
    def __init__(self, *args, **kwargs):
        discord.Client.__init__(self, **kwargs)

    async def on_ready(self):
        print('Success!')


if __name__ == '__main__':
    dc = DiscordClient()
    dc.login(input('email : '), input('password : '), bot=False)
    dc.run()

,错误是:

Traceback (most recent call last):
  File "/Users/jan/PycharmProjects/TheRealUltron/Main.py", line 16, in <module>
    dc.run()
  File "/Users/jan/TheRealZeldaPython/lib/python3.6/site-packages/discord/client.py", line 519, in run
    self.loop.run_until_complete(self.start(*args, **kwargs))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete
    return future.result()
  File "/Users/jan/TheRealZeldaPython/lib/python3.6/site-packages/discord/client.py", line 490, in start
    yield from self.login(*args, **kwargs)
  File "/Users/jan/TheRealZeldaPython/lib/python3.6/site-packages/discord/client.py", line 418, in login
    raise TypeError('login() takes 1 or 2 positional arguments but {} were given'.format(n))
TypeError: login() takes 1 or 2 positional arguments but 0 were given
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x103881fd0>

那么,我做错了什么,或者代码应该是什么样的。我用discord.py做的就是on_message()和一些基本的命令,比如send_message()。

1 个答案:

答案 0 :(得分:0)

client.login 是一个协程,因此应该(未经测试)

await dc.login(input('email : '), input('password : '), bot=False)

请注意,在这种情况下,不需要 bot 参数。 但是,要使用 client.login ,您需要使用 client循环。为避免这种情况,您只需执行

dc.run(email, password)

将同时登录和连接,然后开始循环。

此后,您可以在 on_ready 函数中,从 dc.servers 获取所需的服务器,并通过适当的渠道向其发送消息,例如,“ Hello消息”与 dc.send_message

完成连接后,请在 DiscordClient 类中进行 self.close()

Python 3.4 的工作示例(替换Python 3.6所需的关键字)

import discord
import asyncio
import datetime


class DiscordClient(discord.Client):
    def __init__(self, *args, **kwargs):
        discord.Client.__init__(self, **kwargs)

    @asyncio.coroutine
    def on_ready(self):
        servers = list(self.servers)
        for server in servers:
            if server.name == 'My server':
                break

        for channel in server.channels:
            if channel.name == 'general':
                break

        now = datetime.datetime.now()
        yield from self.send_message(channel, 'Api Success! at ' + str(now))
        print('Success!')
        yield from self.close()


if __name__ == '__main__':
    dc = DiscordClient()
    email = input('email : ')
    password = input('password : ')
    dc.run(email, password)