【问题标题】:How do I send images using discord bot using api如何使用 api 使用 discord bot 发送图像
【发布时间】:2022-07-08 04:38:42
【问题描述】:
import discord
import os
import requests
import json
import random
from replit import db
client = discord.Client()

这对吗?

def get_pic():
  pic_url = requests.get('https://api.thecatapi.com/v1/images/search').json()['url']
  return pic_url


@client.event
async def on_ready():
  print("We have logged in as {0.user}".format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
     return

这是我应该做的。运行时出现错误。 另外,我需要在这段代码中使用 api 密钥吗?

if message.content.startswith('pls catto'):
   pic = get_pic()
   await message.channel.send(content=pic)


client.run(os.environ['TOKEN']) 

      

【问题讨论】:

  • 错误是什么?
  • Traceback(最近一次调用最后):文件“/home/runner/Test-Bot/venv/lib/python3.8/site-packages/discord/client.py”,第 343 行,在_run_event await coro(*args, **kwargs) 文件“main.py”,第 24 行,on_message pic = get_pic() 文件“main.py”,第 10 行,get_pic pic_url = requests.get('api.thecatapi.com/v1/images/search').json()['url'] TypeError: 列表索引必须是整数或切片,而不是 str

标签: python discord discord.py


【解决方案1】:

Traceback(最近一次调用最后):文件“/home/runner/Test-Bot/venv/lib/python3.8/site-packages/discord/client.py”,第 343 行,在 _run_event await coro(* args, **kwargs) 文件“main.py”,第 24 行,on_message pic = get_pic() 文件“main.py”,第 10 行,get_pic pic_url = requests.get('api.thecatapi.com/v1/ images/search').json()['url'] TypeError: list indices must be integers or slices, not str

基于您提交的此错误。这是不言自明的。 只需将 ['url'] 替换为整数或切片。我认为应该将该索引作为参数提供给函数。

【讨论】:

    【解决方案2】:

    我用这段代码随机发送猫模因:D

    @client.command()
    async def cat(ctx:Context):
        value = addon.getRandomCatPic()
        file = discord.File(fp=f"media/cats/{value}")
        await ctx.reply(file=file)
    

    【讨论】:

      【解决方案3】:

      您可以使用discord.File Object 发送文件

      并将文件添加为keywordarg

      您可以进一步了解send函数here

      await channel.send(file=discord.File('path/to/image.png'))
      

      【讨论】:

      猜你喜欢
      • 2021-11-12
      • 2021-07-20
      • 2020-05-13
      • 2019-06-07
      • 2018-08-10
      • 2020-08-31
      • 2020-08-16
      • 2019-08-23
      • 1970-01-01
      相关资源
      最近更新 更多