【问题标题】:Meme Command discord.pyMeme 命令 discord.py
【发布时间】:2021-08-28 11:55:12
【问题描述】:

我的 discord.py 机器人中有 2 个 meme 命令。我正在使用 redditeasy api,因为有人告诉我它更快 asyncpraw 和 praw(这是真的)。​​

我的问题:有没有办法随机化 subreddits?我的意思是,API 应该从给定的 subreddit 列表中随机选取一个 subreddit,然后从该随机选择的 subreddit 中选择一个随机帖子。

我试过了:

random_sub_list = random.choice['Subreddits here']

然后在 subreddit 中传递该变量但不起作用。

这是我的代码:

#memes


@bot.command(aliases = ['m'])
async def meme(ctx):
  post = redditeasy.AsyncSubreddit(subreddit = 'dankmemes',                              client_id='id here',
                                client_secret = 'secret',
                                user_agent = 'memes')

  postoutput = await post.get_post()

  em2 = discord.Embed(title = f'{postoutput.title}')
  url = postoutput.content
  
  em2.set_image(url = url)
  await ctx.send(embed = em2)


#narutomemes


@bot.command(aliases = ['Nmeme', 'NMEME', 'nm', 'NM', 'Nm'])
async def nmeme(ctx):
  post = redditeasy.AsyncSubreddit(subreddit = 'narutomemes',                              client_id='id here',
                                client_secret = 'secret',
                                user_agent = 'memes')

  postoutput = await post.get_post()

  em3 = discord.Embed(title = f'{postoutput.title}')
  url = postoutput.content
  
  em3.set_image(url = url)
  await ctx.send(embed = em3)

【问题讨论】:

  • By 不起作用,我的意思是说我什至没有在终端显示任何错误,并且该命令也没有发送任何 meme。
  • 您可以使用循环将它们附加到列表中
  • lst = [] | for sub in this: 并使用 lst.append(sub)

标签: python discord discord.py


【解决方案1】:

我试过这样的。

def get_post_from_random_subreddit():
    subreddit_name = random.choice(["dankmemes", "narutomemes"])
    subreddit = redditeasy.AsyncSubreddit(
        subreddit=subreddit_name,
        client_secret="secret",
        user_agent="memes"
    )
    post = asyncio.run(subreddit.get_post())
    return f"{post.title} from {post.subreddit_name}"

但如果没有 discord 机器人,它可以完美运行。这些帖子随机来自 2 个子版块。我还使用了你的客户端密码。

小心分享这个秘密。有些人可能会滥用它!

【讨论】:

  • asyncio.run 应该只用作 asyncio 程序的主要入口点,如果您已经在使用 @987654323,在将被多次调用的同步函数中使用它是一个坏主意@为什么不让整个函数异步等待subreddit.get_post
  • 你看我想要它不和谐。如果它在没有不和谐机器人的情况下工作,那有什么意义呢?
  • 也谢谢你的提醒。我实际上忘记删除我要和秘密的东西
【解决方案2】:

老实说,我更喜欢 https://meme-api.herokuapp.com/gimme/(您的 subreddit)这将从您提供的 subreddit 返回一个随机帖子,但 subreddit 必须有照片,(它将以 JSON 形式返回) 这是我当前的 meme 代码

@client.command(pass_context=True, description='Usage: e!meme')
async def meme(ctx):
    content = get("https://meme-api.herokuapp.com/gimme/dankmemes").text
    data = json.loads(content,)
    meme = discord.Embed(title=data['title'], url=data['postLink'], color = colors.purple, timestamp=ctx.message.created_at)
    meme.set_image(url=f"{data['url']}")
    meme.set_footer(text=f'Used by {ctx.author.name}', icon_url=ctx.author.avatar_url)
    await ctx.reply(embed=meme)

https://github.com/D3vd/Meme_Api这是文档

【讨论】:

    猜你喜欢
    • 2019-07-30
    • 2021-07-05
    • 1970-01-01
    • 2021-07-27
    • 2020-11-24
    • 2021-07-10
    • 1970-01-01
    • 2021-08-17
    • 2022-01-12
    相关资源
    最近更新 更多