首页 > 解决方案 > 异步函数不会执行其中的所有内容

问题描述

所以我正在使用 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')

我尝试创建另一个函数只是为了获取推文并返回一条消息,但它没有被调用,所以我不知道我做错了什么。

标签: pythonpython-3.xdiscordtweepydiscord.py

解决方案


在我看来,self.client_id 可能设置不正确。

我玩弄了代码,当我替换id=self.client_idid='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"])

推荐阅读