如何与bot命令一起运行loop.create_task() ?



我有一个异步函数阻塞while循环,它应该是一个后台任务,检查新的推文,并将它们发送到一个特定的不和谐频道。我用bot.loop.create_task(function())开始函数,它就像它应该的那样工作。但是,当我尝试在不协调的情况下执行bot命令时,bot没有响应,也没有发生任何事情。似乎后台任务阻塞了一切。下面是后台任务:

async def user_tweets():
await bot.wait_until_ready()
while True:
with open('data/data.json') as account_file:
data = json.load(account_file)
# loop for every user
for discord_user in data:
for twitter_users_dict in data[discord_user]:
twitter_user = ''.join([key for key in twitter_users_dict.keys()])
value = twitter_users_dict.get(twitter_user)
try:
tweet = api.user_timeline(screen_name=twitter_user,
# 200 is the maximum allowed count
count=200,
include_rts=value['retweets'],
tweet_mode='extended',
exclude_replies=not value['replies'],
include_entities=True
)
except tweepy.TweepError:
twitter_feed_channel = bot.get_channel(779894858478649344)
await twitter_feed_channel.send('Request limit is probably exceeded, waiting 5 min before trying again')
time.sleep(300)
continue
for entry in data[discord_user]:
if entry.get(twitter_user):
entry[twitter_user]['Last tweet'] = info.id
with open('data/data.json', 'w') as account_file:
json.dump(data, account_file)
twitter_feed_channel = bot.get_channel(829886945982939207)
user_to_ping = await bot.fetch_user(discord_user)
await twitter_feed_channel.send(f'{user_to_ping.mention} https://twitter.com/twitter/statuses/{info.id}')
print('sent ' + discord_user + twitter_user + str(value))
time.sleep(1)

是我做错了什么还是有更好的方法来做这件事?我只是想有一个后台任务运行时,bot运行,也有bot响应命令。

将阻塞与异步代码混合并不是最好的主意,我会将每个阻塞函数提交给单独的线程/进程。尽管如此,您可以通过以下方式运行阻塞协程:

import asyncio
async def user_tweets():
...

async def run_blocking_coro(coro):
loop = asyncio.get_event_loop()
def wrapper():  # submit this to a thread
fut = asyncio.run_coroutine_threadsafe(coro, loop)
return fut.result()
return await loop.run_in_executor(None, wrapper)  # asyncio.to_thread for python 3.9+

asyncio.create_task(run_blocking_coro(user_tweets())

相关内容

最新更新