【问题标题】:Sending qr codes to discord user向不和谐用户发送二维码
【发布时间】:2021-11-14 19:49:58
【问题描述】:

我的不和谐机器人在某个命令后创建二维码。但是我无法将此二维码作为消息发送给用户:

import qrcode

def create_qr_code(string : str):

    qr = qrcode.make(string)
    return qr


# sending qr to user
qr_code = create_qr_code('some text')
# check if qr_code is None
print(qr_code)
await ctx.send(file=discord.File(fp=qr_code))

我的print 语句返回类似

<qrcode.image.pil.PilImage object at 0x000001BD735FCF28>,

这很好,告诉我二维码的创建是成功的。 我想知道为什么发送它似乎不起作用。

【问题讨论】:

  • 您不能向频道发送 base64 编码字符串吗?或作为一个blob
  • 为了简单起见,为什么在上传临时文件后必须删除它们......?
  • 不,这不是问题,我认为使用save 功能可以永久保存

标签: python file discord bots qr-code


【解决方案1】:

您可以使用名为qrcode 的包,然后使用此代码:

async def qrcode(self, ctx, *, url):
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=10,
            border=4,
        )
        qr.add_data(str(url))
        qr.make(fit=True)
        img = qr.make_image(fill_color="black",
                            back_color="white").convert('RGB')
        img.save('qrcode.png')
        await ctx.send(file=discord.File('qrcode.png'))

顺便说一句,如果您想继续使用 PyQRCode,请查看 pypi 文档,看起来您可以这样做:

qr_code.png('code.png', scale=6, module_color=[0, 0, 0, 128], background=[0xff, 0xff, 0xcc])

保存它。

【讨论】:

  • 我编辑了我的代码,我现在使用qrcode
  • 我找到了一个可行的解决方案here
【解决方案2】:

实际上,我自己使用this 解决方案找到了一个可行的解决方案:

首先我创建一个二维码并返回这个对象

import qrcode

def create_qr_code(string : str):

    qr_code = qrcode.make(string)
    return qr_code

我现在可以使用BytesIO() 将此二维码作为二进制文件发送到 Discord:

import io

def some_other_function():

    qr_code = create_qr_code('my string')

    with io.BytesIO() as image_binary:
        qr_code.save(image_binary, 'PNG')
        image_binary.seek(0)
        await ctx.send(file=discord.File(fp=image_binary, filename='qr.png'))

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 2020-11-12
    • 2020-07-28
    • 2022-01-08
    • 2022-11-16
    • 2021-04-03
    • 2021-04-20
    • 2021-05-08
    • 2022-10-13
    相关资源
    最近更新 更多