如何解决如何在 discord.py 和 Tweepy 之间进行通信?
我的代码类似于这个例子:
import discord
import tweepy
import asyncio
class Client(discord.Client):
async def on_ready(self):
print("ready")
global GUILD
GUILD = discord.utils.get(self.guilds,name = "Any Guild")
class TweepyStream(tweepy.Stream):
def on_connect(self):
print("connceted")
def on_status(self,status):
print(status.text)
channel = discord.utils.get(GUILD.channels,name = "twitter-posts")
asyncio.run(channel.send(status.text))
#From here the Discord message should be send
auth = tweepy.OAuthHandler(keys)
auth.set_access_token(tokens)
global api
api = tweepy.API(auth)
follow_list = []
follow = int(api.get_user(screen_name = "Any User").id)
print(follow)
follow_list.append(follow)
print(str(follow_list))
stream = TweepyStream(tokens and keys)
stream.filter(follow = follow_list,threaded=True) #track = track,client = Client()
client.run(token)
我尝试接收 Twitter 帖子并将它们发送到 Discord 频道,但它不起作用。我该怎么做(也许没有 asyncio)? 或者有没有办法使用 Python Twitter API,它适用于异步函数?
我的错误:
Stream encountered an exception
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\tweepy\streaming.py",line 133,in _connect
self.on_data(line)
File "C:\Python39\lib\site-packages\tweepy\streaming.py",line 387,in on_data
return self.on_status(status)
File "c:\Users\morit\Desktop\FLL 2021 Bot\DiscordBot\DiscordBotV0.7\example.py",line 18,in on_status
asyncio.run(channel.send(status.text))
File "C:\Python39\lib\asyncio\runners.py",line 44,in run
return loop.run_until_complete(main)
File "C:\Python39\lib\asyncio\base_events.py",line 642,in run_until_complete
return future.result()
File "C:\Python39\lib\site-packages\discord\abc.py",line 1065,in send
data = await state.http.send_message(channel.id,content,tts=tts,embed=embed,File "C:\Python39\lib\site-packages\discord\http.py",line 192,in request
async with self.__session.request(method,url,**kwargs) as r:
File "C:\Python39\lib\site-packages\aiohttp\client.py",line 1117,in __aenter__
self._resp = await self._coro
File "C:\Python39\lib\site-packages\aiohttp\client.py",line 448,in _request
with timer:
File "C:\Python39\lib\site-packages\aiohttp\helpers.py",line 635,in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
解决方法
asyncio.run
创建一个新的事件循环。您需要使用 discord.Client
使用的现有事件循环。您可以使用 Client.loop
、asyncio.get_running_loop
或 asyncio.get_event_loop
检索它。
您可能还应该使用 asyncio.run_coroutine_threadsafe
。
如果您在 master 分支上使用当前最新的 Tweepy 开发版本,设置发布为 v4.0,看起来您是这样,那么您也可以考虑使用 AsyncStream
>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。