在 discord py 上有主机器人 class 和没有 class 有什么区别?
What is the difference between having a main bot class versus no class on discord py?
对于 discord python 机器人,我似乎找不到很好的答案,而且文档实际上随机使用了这两个示例。在 bot.py 中使用机器人 class 与在没有 class 的情况下启动机器人之间的主要区别是什么?请参阅下面的示例
带有 class 的示例机器人:
import discord
from discord.ext import commands
class MyBot(commands.Bot):
async def on_ready():
# ready
bot = MyBot(command_prefix='!')
bot.run(token)
没有 class 的常规机器人示例:
import discord
from discord.ext import commands
if __name__ == "__main__":
bot = commands.Bot(command_prefix='!')
async def on_ready():
# ready
bot.run(token)
据我所知,这两个示例都有效并且做同样的事情,但就像我说的那样,我似乎无法找到一个很好的答案来解决两者之间的差异。
创建自己的 class 有几个优点。
首先,您可以将 MyBot
class 导入到另一个文件中。因此,如果您想将您的项目拆分为多个文件(可能两个人正在处理同一个项目),一个人可以处理 MyBot
class 而另一个人可以导入它。
my_bot.py
import ...
class MyBot(commands.Bot):
...
test.py
from my_bot import MyBot
bot = MyBot()
其次,您将能够更轻松地更改 MyBot
中的函数。现在你的 async def on_ready():
函数在第二个例子中没有做任何事情,即使里面有代码。如果你把它放在 MyBot
class 里面,当你的机器人准备好时它会被调用。参见 on_ready()
比较
class MyBot(commands.Bot):
async def on_ready():
print('connected to server!')
bot = MyBot(command_prefix='!')
bot.run(token)
至
if '__name__' == '__main__':
bot = commands.Bot(command_prefix='!')
async def on_ready():
print('connected to server!')
bot.run(token)
在第二个例子中,它永远不会说“已连接到服务器!”因为该代码不会 运行。如果您使用 on_ready()
调用它,那并不意味着您已连接到服务器。关闭您的互联网连接,您会看到。
当然,您可能会做一些比打印消息更有用的事情。也许您会将连接日志写入文件或其他内容。
对于 discord python 机器人,我似乎找不到很好的答案,而且文档实际上随机使用了这两个示例。在 bot.py 中使用机器人 class 与在没有 class 的情况下启动机器人之间的主要区别是什么?请参阅下面的示例
带有 class 的示例机器人:
import discord
from discord.ext import commands
class MyBot(commands.Bot):
async def on_ready():
# ready
bot = MyBot(command_prefix='!')
bot.run(token)
没有 class 的常规机器人示例:
import discord
from discord.ext import commands
if __name__ == "__main__":
bot = commands.Bot(command_prefix='!')
async def on_ready():
# ready
bot.run(token)
据我所知,这两个示例都有效并且做同样的事情,但就像我说的那样,我似乎无法找到一个很好的答案来解决两者之间的差异。
创建自己的 class 有几个优点。
首先,您可以将 MyBot
class 导入到另一个文件中。因此,如果您想将您的项目拆分为多个文件(可能两个人正在处理同一个项目),一个人可以处理 MyBot
class 而另一个人可以导入它。
my_bot.py
import ...
class MyBot(commands.Bot):
...
test.py
from my_bot import MyBot
bot = MyBot()
其次,您将能够更轻松地更改 MyBot
中的函数。现在你的 async def on_ready():
函数在第二个例子中没有做任何事情,即使里面有代码。如果你把它放在 MyBot
class 里面,当你的机器人准备好时它会被调用。参见 on_ready()
比较
class MyBot(commands.Bot):
async def on_ready():
print('connected to server!')
bot = MyBot(command_prefix='!')
bot.run(token)
至
if '__name__' == '__main__':
bot = commands.Bot(command_prefix='!')
async def on_ready():
print('connected to server!')
bot.run(token)
在第二个例子中,它永远不会说“已连接到服务器!”因为该代码不会 运行。如果您使用 on_ready()
调用它,那并不意味着您已连接到服务器。关闭您的互联网连接,您会看到。
当然,您可能会做一些比打印消息更有用的事情。也许您会将连接日志写入文件或其他内容。