python - 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 频道,但它不起作用。我该怎么做(也许没有异步)?或者有没有办法使用 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
推荐阅读
- r - R:sparklyr 中的组(“sum”、“count distinct”、“mean”)
- javascript - JS中的评论是如何分类的?
- python - 在 Python 中使用 XLwings 从下拉列表中选择
- excel - 索引和匹配从上面的行返回答案
- docker - conda cache for docker
- spring-boot - 使用 JIB 插件对 Spring Boot 应用程序进行 Dockerizing
- angular - Angular 2 元素下划线
- git - 我需要暂时撤消合并,以便稍后再尝试
- google-api - 可以使用 Google Calendar API 创建可扩展的日程安排服务吗?
- python-3.x - 为什么我尝试抓取文本元素的值返回零?