Discord Bot GCP 云功能

时间:2021-05-22 11:08:22

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

我想结合 GCP Cloud SchedulerCloud 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 中包含了 discord,但是,当我测试该函数时出现以下错误: error messages

  1. 运行时错误:线程“ThreadPoolExecutor-0_0”中没有当前事件循环。,
  2. 运行时错误:set_wakeup_fd 仅适用于主线程
  3. 类型错误:bot_function() 接受 0 个位置参数,但给出了 1 个

1 个答案:

答案 0 :(得分:3)

如果您考虑具有这样的时间表的 webhooks 会更好。

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

enter image description here

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