python - 异步函数不会执行其中的所有内容
问题描述
所以我正在使用 python3.7 和 discord.py 制作一个 Discord 机器人。它的功能之一是您可以使用 tweepy 库从 discord 发送推文,这是我的代码:
@bot.command(name='tw',help='tuitea')
@commands.has_role("chechu's")
async def tweet(ctx, *, args):
tweepy.update_status(args)
tweet = self.client.user_timeline(id = self.client_id, count = 1)[0]
await ctx.send('tweet sent')
我的问题是,在发送推文后(这很有效),我想返回一条消息,其中包含指向它刚刚发布的推文的链接。正如你在上面看到的,我试图得到最后一条推文,tweet = self.client.user_timeline(id = self.client_id, count = 1)[0]
但执行甚至没有到达await ctx.send('tweet sent')
我尝试创建另一个函数只是为了获取推文并返回一条消息,但它没有被调用,所以我不知道我做错了什么。
解决方案
在我看来,self.client_id 可能设置不正确。
我玩弄了代码,当我替换id=self.client_id
为id='59553554'
(Wendy 的 twitter 帐户 ID)时,它运行良好:
推文 = client.user_timeline(id='59553554', count = 1)[0]
我还尝试使用 screen_name 属性,它也返回了 Wendy's 发送的最后一条推文:
tweet = client.user_timeline(screen_name='@Wendys', count = 1)[0]
为了解决您的问题,我会检查以确保将 self.client_id 正确设置为帐户正在使用的现有 ID,或者只是插入您发布时使用的屏幕名称。
就返回推文的链接而言,您可以使用推文的属性构建推文的 URL:
等待 ctx.channel.send(" https://twitter.com/ " + tweet.user.screen_name + "/status/" + tweet.id_str)
这是完整的代码:
import discord
import tweepy
import os
from discord.ext import commands
prefix = "$"
bot = commands.Bot(command_prefix=prefix)
auth = tweepy.OAuthHandler(os.environ["TWITTER_API_KEY"], os.environ["TWITTER_API_SECRET"])
client = tweepy.API(auth)
@bot.command(pass_context=True)
async def tweet(ctx):
tweet = client.user_timeline(id='59553554', count = 1)[0]
await ctx.channel.send("https://twitter.com/" + tweet.user.screen_name + "/status/" + tweet.id_str)
tweet = client.user_timeline(screen_name='@Wendys', count = 1)[0]
await ctx.channel.send("https://twitter.com/" + tweet.user.screen_name + "/status/" + tweet.id_str)
bot.run(os.environ["DISCORD_TOKEN"])
推荐阅读
- class - SwiftUI 使用 Core Data 在类中进行计算
- python - Python BLE 发现所有 UUID 特征
- image - 在 Flutter 中本地缓存 base64 图像
- javascript - 有人能告诉我为什么这段代码不叫我那个函数吗?
- mysql - Docker 卷数据被存储两次?
- visual-studio-code - 如何在 VS Code 中更改我的字体,因为显然这给了我错误的输出
- python-3.x - 如何在根窗口透明的情况下使画布不透明?
- visual-studio - 将 MS-Project 加载项发布到 Microsoft Store?
- intellij-idea - 如何使 IntelliJ 运行窗口工具侧边栏消失以节省空间?
- java - 如何使用 MongoDB Java 查找字段的重复数?