首页 > 解决方案 > 如何让python读取机器人在discord上发送的消息

问题描述

Discord 上有一个机器人可以让你“种植”自己的小像素艺术植物,但你必须至少每两天给它们浇水一次,以免它们死亡。我编写了一个小代码,通过向机器人所在的 Discord 频道发送消息,每 15 分钟给我的植物浇水。目前,我必须在我创建的文档中插入我的植物名称,以便 python 可以读取它,但是,如果它可以自己获取植物名称,我希望它。如果您向机器人发送一条消息,称“p.plants”到机器人所在的频道,它会向您发送一条消息,其中包含您的植物列表。如何让 python 读取该消息并将所有植物放在一个列表中?PS:我是一个绝对的初学者,这是我的第一个“真正的”项目。到目前为止,这是我的代码:

import itertools
import sys
import threading
import time
import requests
import toml
from tqdm import tqdm


counter = "plants"
line_count = 0
with open(counter, "r") as files:
    for _ in files:
        line_count += 1

with open("config.toml") as f:
    config = toml.load(f)

token = config["token"]
channel = config["ChannelID"]


def countdown(start):
    return list(reversed(range(start + 1)))


def main():
    while True:
        start = input("Would you like to wake up the farmer?(Y/N) ").upper()
        if start == "Y":
            payload = {
                'content': "p.plants"
            }
            header = {
                'authorization': token
            }
            _ = requests.post(channel, data=payload, headers=header)
            loop_counter_message = input(
                "Would you like the farmer to send messages to your channel telling you how many "
                "times he has watered your plants? (Y/N)").upper()
            done = False

            def animate():
                for c in itertools.cycle(['.', '..', '...', '....', '.....']):
                    if done:
                        break
                    sys.stdout.write('\rWaking up the farmer ' + c)
                    sys.stdout.flush()
                    time.sleep(1)
                sys.stdout.write('\rDone! The farmer is awake and will now start watering your plants!     ')
                time.sleep(0.5)

            t = threading.Thread(target=animate)
            t.start()
            time.sleep(5)
            done = True
            loop_counter = 0
            while loop_counter >= 0:
                payload_counter = 0
                while payload_counter < line_count:
                    plants = open("plants", "r")
                    time.sleep(2)
                    print("")
                    for plant in plants.readlines():
                        payload = {
                            'content': "p.water " + plant
                        }
                        print("Watering " + plant + "...")
                        header = {
                            'authorization': token
                        }
                        _ = requests.post(channel, data=payload, headers=header)
                        payload_counter += 1
                        time.sleep(1)
                        if payload_counter == line_count:
                            payload = {
                                'content': "p.exp"
                            }
                            header = {
                                'authorization': token
                            }
                            _ = requests.post(channel, data=payload, headers=header)
                            loop_counter += 1
                            print("")
                            print("All your plants have been watered!")
                            print("")
                            print("If at any time you wish to stop the farmer, press [E] for 1 second")
                            if loop_counter != 1:
                                print("So far, the farmer has watered your plants " + str(loop_counter) + " times.")
                                if loop_counter_message == "Y":
                                    payload = {
                                        'content': "So far, the farmer has watered your plants " + str(loop_counter)
                                                   + " times. "
                                    }
                                    header = {
                                        'authorization': token
                                    }
                                    _ = requests.post(channel, data=payload, headers=header)
                            else:
                                print("So far, the farmer has watered your plants " + str(loop_counter) + " time.")
                                if loop_counter_message == "Y":
                                    payload = {
                                        'content': "So far, the farmer has watered your plants " + str(
                                            loop_counter) + " time."
                                    }
                                    header = {
                                        'authorization': token
                                    }
                                    _ = requests.post(channel, data=payload, headers=header)
                            for _ in tqdm(countdown(2619)):
                                plants.close()
                                time.sleep(0.3333333)

        elif start == "N":
            print("Ok, the farmer will stay asleep for now")
            time.sleep(2)
            exit()
        else:
            print("Invalid command")


if __name__ == '__main__':
    main()

标签: pythondiscord

解决方案


推荐阅读