- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个用 非重写 版本的 discord.py 编写的 Discord 机器人,它发送类似心跳的消息(以及其他内容)。我不知道我是否理解正确,但通过测试,我发现我需要在 main.py
文件中包含 async def heartbeat()
函数。
摘自 main.py
(heartbeat 按预期工作):
[...]
import asyncio
import datetime
from configparser import ConfigParser
startup_time = datetime.datetime.utcnow()
[...]
async def heartbeat():
await bot.wait_until_ready()
heartbeat_config = ConfigParser()
heartbeat_config.read('./config/config.ini')
hb_freq = int(heartbeat_config.get('Heartbeat', 'hb_freq')) # frequency of heartbeat message
hb_channel = heartbeat_config.get('Heartbeat', 'hb_channel') # target channel of heartbeat message
hb_channel = bot.get_channel(hb_channel) # get channel from bot's channels
await bot.send_message(hb_channel, "Starting up at: `" + str(startup_time) + "`")
await asyncio.sleep(hb_freq) # sleep for hb_freq seconds before entering loop
while not bot.is_closed:
now = datetime.datetime.utcnow() # time right now
tdelta = now - startup_time # time since startup
tdelta = tdelta - datetime.timedelta(microseconds=tdelta.microseconds) # remove microseconds from tdelta
beat = await bot.send_message(hb_channel, "Still running\nSince: `" + str(startup_time) + "`.\nCurrent uptime: `" + str(tdelta))
await asyncio.sleep(hb_freq) # sleep for hb_freq seconds before initialising next beat
await bot.delete_message(beat) # delete old beat so it can be replaced
[...]
if __name__ == "__main__":
global heartbeat_task
heartbeat_task = bot.loop.create_task(heartbeat()) # creates heartbeat task in the background
bot.run(token) # run bot
我有一些命令应该与创建的 heartbeat_task
交互,但它们在不同的模块中,称为 dev.py
(位于与main.py
).
摘自dev.py
:
[...]
from main import heartbeat_task, heartbeat
[...]
@commands.group(pass_context=True)
async def heart(self, ctx):
if ctx.invoked_subcommand is None:
return
@heart.command(pass_context=True)
async def stop(self, ctx):
# should cancel the task from main.py
heartbeat_task.cancel()
await self.bot.say('Heartbeat stopped by user {}'.format(ctx.message.author.name))
@heart.command(pass_context=True)
async def start(self, ctx):
# start the heartbeat if it is not running
global heartbeat_task
if heartbeat_task.cancelled():
heartbeat_task = self.bot.loop.create_task(heartbeat())
await self.bot.say('Heartbeat started by user {}'.format(ctx.message.author.name))
else:
return
[...]
这些命令在它们是 main.py
的一部分时工作得很好(当然需要进行必要的调整,比如删除 self
、导入等),但是因为我希望所有与开发人员相关的命令都进入它们自己的模块,所以我尝试移动它们。
当我尝试加载模块时出现以下错误:
ImportError:无法导入名称“heartbeat_task”。
从 dev.py
中删除该导入会导致成功加载模块,但在使用任一命令时,控制台都会抛出错误:
NameError:未定义名称“heartbeat_task”
这可以追溯到 heartbeat_task.cancel()
行(在 heart stop
的情况下//if heartbeat_task.cancelled():
(在 heart start
的情况下)。
现在我的问题。我怎样才能在 main.py
中使用异步 heartbeat()
但通过 dev.py
模块中的命令影响任务?
如果我不能,有什么可行的替代方案可以将命令保留在 dev.py
中(函数本身不需要保留在 main.py
中)但最好留在那里)?
(我已经搜索了很长时间,但找不到像我这样的问题或恰好适合我的解决方案)
最佳答案
在 cog 中拥有后台任务的最简单方法是向 cog 添加一个 on_ready
协程来启动后台任务,而不是手动启动它:
class MyCog:
def __init__(self, bot):
self.bot = bot
async def heartbeat(self):
...
async def on_ready(self):
self.heartbeat_task = self.bot.loop.create_task(heartbeat())
@commands.command(pass_context=True)
async def stop(self, ctx):
self.heartbeat_task.cancel()
await self.bot.say('Heartbeat stopped by user {}'.format(ctx.message.author.name))
def setup(bot):
bot.add_cog(MyCog(bot))
请注意,您不需要用 cog 中的任何东西装饰 on_ready
,add_cog
机制将根据它的名称来拾取它。
关于python - 使用子模块 [discord.py] 中的命令与后台任务交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52334477/
我使用的是 Windows 8.1 和 Python 2.7,我在特定文件路径中设置了所有文件(希望正确),但每当我运行 python manage.py runserver 时,我都会收到此错误。
背景: 我有一个像这样的目录结构: Package/ setup.py src/ __init__.py __main__.py cod
我从这个线程运行了一个示例代码。 How to properly use coverage.py in Python? 但是,当我执行此命令时 py.test test.py --cov=sample
IPython 0.13.1 文档说: $ ipython -h ... Usage ipython [subcommand] [options] [files] If invoked
我写了一个网站,让我困惑的是当我运行这个网站时,首先我需要启动应用程序,所以有 3 种方法: sudo python xxx.py python xxx.py xxx.py 每一个我都不清楚怎么用,目
我不确定为什么它不起作用,这可能是一个您无法解决的问题,但我只是想知道为什么它不起作用。如果我浪费了您的时间,或者没有正确地提出问题,我很抱歉,我 16 岁,对 Python 还算陌生。 在main.
鉴于以下情况:models.py from .managers import PersonManager from django.db import models class Person(model
有没有办法将参数传递给 web.py 处理程序类构造函数? 例如。这些参数可能来自命令行(当主 web.py 脚本运行时),在第一个参数(作为端口号)之后 最佳答案 当然,这取决于你的意思。毕竟都是p
我对 python/django 编程很陌生,因为我没有编程背景。我正在在线上课,我只想确切地知道 manage.py 文件的作用。我试过用谷歌搜索它,但除了在 django-admin.py 周围放
我想将类别及其子类别保存到数据库中,这里每个类别都有多个子类别。您能帮我保存与类别相对应的用户、类别和多个子类别吗?Models.py、Serializers.py、Views .py 并附加传入请求
所以我的机器人开始有很多命令,并且在 main.py 上变得有点困惑。我知道有一种方法可以将命令存储在其他文件中,然后在 discord.js 上触发它们时将它们应用于 main.py。在 disco
我正在尝试制作一个类似于 mee6 的 Discord 机器人,因为它会按特定时间间隔计算用户在我的 Discord 服务器中发送的消息。我已经在网上搜索过,但即使有类似的问题也找不到我要找的东西。例
我正在尝试制作一个机器人,它根据特定 channel 中的消息创建线程。如果有在 discord.py 中的文本 channel 中创建线程的方法,请告诉我。 最佳答案 是的,但有一个问题。 当前版本
我一直在尝试制作一个命令来显示一些信息,然后当我对表情使用react时,它应该会显示另一组信息。 我尝试使用 this 的部分内容,特别是第 335 到 393 行的部分让它工作。但是,它什么也不做。
这是我试过的代码: @client.event async def on_message(message): if client.user.mention in message.content
我试过这段代码,机器人说猜但没有回应我的猜测。 @commands.command() async def game(self, ctx): number = random.randint(0
我决定尝试让我的不和谐机器人播放音乐,但我已经卡住了。主要是因为我找不到任何资源来帮助当前版本,我一直在从文档中获取所有内容。但是,我不知道如何检查机器人是否已连接到语音 channel 。 我试过
我在一个目录中有三个文件: # Untitled-1.py print("UTITLEDPY") if __name__== "__main__": from telegram.ext imp
我对 python 相当陌生,并且一直只使用 Jupyter Notebooks。当我需要运行我已保存在计算机中某处的 .py 文件时,我通常所做的就是使用魔术命令 %run %run '/home/
我有 Django 1.4 和 Python 2.6.6当我使用“django-amdin.py startproject djproject”时,请按照网页中的步骤操作 https://www.ib
我是一名优秀的程序员,十分优秀!