【问题标题】:Discord Bot GCP Cloud FunctionsDiscord Bot GCP 云功能
【发布时间】:2021-05-22 11:08:22
【问题描述】:

我想结合 GCP Cloud Scheduler 和 Cloud Functions 每周向 Discord 频道发送消息。

理想情况下,调度程序将使用 HTTP 触发器,然后云函数将运行,将消息发送到特定通道。

ma​​in.py:

import discord

def bot_function():
  client = discord.Client()
  channel_id = "CHANNEL_ID"
  @client.event
  async def on_ready():
      await client.get_channel(channel_id).send("TEST MESSAGE")
      
  client.run("API_KEY")

我在 requirements.text 中包含了不和谐,但是,我在测试函数时遇到了以下错误: error messages:

  1. RuntimeError:线程 'ThreadPoolExecutor-0_0' 中没有当前事件循环。,
  2. RuntimeError: set_wakeup_fd 仅在主线程中有效
  3. TypeError: bot_function() 接受 0 个位置参数,但给出了 1 个

【问题讨论】:

  • 你可以在 python 中使用 requests 向 discord 的 API 发送 HTTP 请求来代替发送消息

标签: python google-cloud-functions discord.py google-cloud-scheduler


【解决方案1】:

如果您考虑使用这样的时间表的 webhook 会更好。

从您的服务器设置中获取 webhook url

import requests #dependency

url = "<your url>" #webhook url, from here: https://i.imgur.com/aT3AThK.png

data = {}
#for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
data["content"] = "message content"
data["username"] = "custom username"

#leave this out if you dont want an embed
data["embeds"] = []
embed = {}
#for all params, see https://discordapp.com/developers/docs/resources/channel#embed-object
embed["description"] = "text in embed"
embed["title"] = "embed title"
data["embeds"].append(embed)

result = requests.post(url, json=data, headers={"Content-Type": "application/json"})

try:
    result.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)
else:
    print(f"Payload delivered successfully, code {result.status_code}.")

#result: https://i.imgur.com/DRqXQzA.png

【讨论】:

    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 2020-01-25
    • 2018-03-11
    • 2021-07-15
    • 2021-08-19
    • 2022-09-01
    • 2020-11-13
    • 2022-08-19
    相关资源
    最近更新 更多