# [零基础上手] Discord 自动参加抽奖机器人(云端稳定版)

By [scientist](https://paragraph.com/@scientist) · 2022-02-09

---

本篇教学会带大家部署一个自动参加Discord 抽奖机器人，会使用云端主机Google Cloud Function，好处是不会面临电脑关机时机器人就休息的情况，然后Google 也有提供一定使用额度内免费，所以基本上是完全零成本免费部署，让大家都可以解放双手和注意力，不会再错过任何Discord 的抽奖项目！

会有这篇文章的诞生，主要感谢Fomo dog 社群中的meta Simon 和saibalmars 狗友们，不断地改进和修正程式码(如下连结)，才会有今天的Discord 抽奖机器人(云端稳定版本)

1\. 申请Google Cloud Platform
---------------------------

首先我们要申请Google Cloud Platform 的帐号，可以从这里[进入](https://console.cloud.google.com/getting-started)，Google 目前有提供3 个月内300 美金的额度使用，而我们这次会使用GCP 里面的Google Cloud Function，以这次部署的程式的每用使用量来说，每月的花费在0 块台币以内。

![](https://storage.googleapis.com/papyrus_images/a1eae51de722fac9d6447b4d4261e26cd84cad466ad7d7b1780185c11ca92758.png)

接下来建立第一个专案，专案名称可以依自己喜好命名

![](https://storage.googleapis.com/papyrus_images/7a296cf7093caa636104f6a138bd11ac34d2f39287a06adc4e95fb416c40c8f8.png)

2\. 创建Cloud Function
--------------------

接下来在搜寻栏中搜寻“Cloud Function”，并且选择建立函式

![](https://storage.googleapis.com/papyrus_images/193b9ff1f21c6ca074a7b093ff6cbebd2d0ef37b1cba215d7200ee24cfbe4969.png)

创建Cloud Function – Step 1

1.  函式名称：可以自由填写
    
2.  选择区域：可以挑选自己喜欢的主机所在地，这边选择asia-east1 台湾
    
3.  触发条件：选择Cloud Pub / Sub
    
4.  建立一个Pub / Sun 主题> 输入主题ID (可随意填) > 选择建立主题
    
5.  选择储存
    
6.  并点选下一步
    

![](https://storage.googleapis.com/papyrus_images/c40078daf1d0d7afdd344b1561eacfd5cf6e4bb04e9e1ba7842303750639f50c.png)

创建Cloud Function – Step 2

1.  选择启用API
    
2.  选择执行阶段Python 3.9
    

![](https://storage.googleapis.com/papyrus_images/02dc3a7cf2419376a73da427c91e5dda3caf4e2f154ab61da0c66024105fc9f4.png)

创建Cloud Function – Step 3

1.  选择main.py
    
2.  输入进入点：getlist
    
3.  输入我们的抽奖机器人程式码
    

![](https://storage.googleapis.com/papyrus_images/eb04f1971359cd4c6b3d57b9ceadb1bb9539143d2811293e691c4cb072c46385.png)

步骤3 里面的完整程式码如下： (请在bots\_setting 中加入自己想要追踪的抽奖频道，关于参数设定可以参考Simon 的[这篇](https://medium.com/@metasimon/discord-%E6%8A%BD%E7%8D%8E%E6%A9%9F%E5%99%A8%E4%BA%BA%E9%80%B2%E9%9A%8E%E7%89%88-%E6%94%AF%E6%8F%B4%E5%B8%B3%E8%99%9F%E5%A4%9A%E9%96%8B-%E5%A4%9A%E9%A0%BB%E9%81%93-%E5%A4%9A%E9%97%9C%E9%8D%B5%E5%AD%97%E9%83%A8%E4%BD%8D%E5%81%B5%E6%B8%AC-9950914a2784))

    import requests
    import json
    import random
    import time
    from datetime import datetime
    
    def getlist(event, context):
    
        # You can add more than one bot if you have multiple discord accounts.
        bots_setting = [
            {
                "name": "bot1",
                "authorizations": [
                        "xxxxxxx.xxxxxxx",
                    ],  # Please remember to put in your discord message authorization code
                        # spearate by comma if you have more than one token.
                "channel_lists": [
                    {
                        "name": "Alpha Shark",  # Nickname for the channel
                        "settings": {
                            "channel_id": "927557825486536764",     # Channel's discord ID
                            "lottery_keyword": "React with \\ud83c\\udf89 to enter!",      # Lottery keyword to detect:  "React with 🎉 to enter!"
                            "emojis_to_click": ["%F0%9F%8E%89"]     # emoji to click
                        }
                    }
                ]
            }
        ]
    
        limit=10
        
        for bot in bots_setting:
            for auth in bot["authorizations"]:
                header = {
                    "Authorization": auth,
                    "Content-Type": "application/json",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36",
                }
                for channel in bot["channel_lists"]:
                    url = "https://discord.com/api/v9/channels/{}/messages?limit={}".format(channel["settings"]["channel_id"], limit)
                    try:
                        res = requests.get(url=url, headers=header)
                        messages_json = json.loads(res.text)
                        for message in messages_json:
                            try:
                                if channel["settings"]["lottery_keyword"] in json.dumps(message):
                                    is_lottery_post = True
                                else:
                                    is_lottery_post = False
    
                                if is_lottery_post:
                                    print("-------------Lottery captured!--------------")
                                    print("Date:", datetime.now())
                                    print("Channel:", channel["name"])
                                    print("Message ID:", message["id"])
                                    print("Content:", message["content"])
                                    print("embeds:", message["embeds"])
                                    for emoji in channel["settings"]["emojis_to_click"]:
                                        url = "https://discord.com/api/v9/channels/{}/messages/{}/reactions/{}/%40me".format(
                                            channel["settings"]["channel_id"], message["id"], emoji)
                                        requests.put(url=url, headers=header)
                                        time.sleep(1)
    
                            except:
                                print("Failed to expand messages.")
                                pass
                    except:
                        print("Failed to get discord message.")
                        pass
    

在步骤4 里面的requirements.txt 里面加入requests，完整程式码如下：

    # Function dependencies, for example:
    # package>=version
    requests
    

最后点击部署！但程式目前还不会自动执行，我们还要加上触发时间

3\. 设定触发时间
----------

1.  在搜寻栏中，搜寻cloud scheduler，并建立一个新工作
    
2.  名称：Hourly (这边可以随意填)
    
3.  地区：选择北京
    
4.  频率：30 \* \* \* \* (这个意思是每个小时会执行一次)
    
5.  时区：世界标准时间
    
6.  Pub / Sub 主题：选择我们稍早在创立Cloud function 时所创造的hourly 的Pub / Sub
    
7.  讯息内文：这边可以随便填
    

![](https://storage.googleapis.com/papyrus_images/2227c4e03c2004527901ebc3fba69d875d8ca9efbbeffa9f6ef98fc837d9c490.png)

最后选择建立！就完成触发条件设定啰

4\. 如何检查Discord 抽奖机器人
---------------------

如何确定程式有执行？基本上只要没事去看一下Discord 抽奖频道，确认有没有点击抽奖就可以了

担心的话可以到Cloud Function > 纪录里面，可以看到程式执行过程(如下图)

![](https://storage.googleapis.com/papyrus_images/4d5fec8b18b65d4c608dac331de5c9e7cc6297019f50a1a268ef8a71535170ab.png)

那\[零基础上手\] Discord 自动参加抽奖机器人(云端稳定版) 就到这边感谢收看，如文章内容有误请不吝指正！

---

*Originally published on [scientist](https://paragraph.com/@scientist/discord-2)*
