首页 > 解决方案 > Python如何每30秒运行一次脚本,然后发送不和谐的消息

问题描述

我正在开发一个检查特定以太地址并检查令牌传输的机器人。一切都完成了 api 和东西,但我无法检查部分工作。它检查 addrs 并输出是否更改,但如何每​​ 30 秒运行一次,并且该输出不和谐。

我的代码:

    import requests, time, json, sys, discord
    result = requests.get('myapi')

    result.json()
    results = "soon:tm:"
    
    def price_of_gas(inp):
        def recursive_function(inp):
            if type(inp) is list:
                for i in inp:
                    ans = recursive_function(i)
                    if ans != None:
                        return ans
            elif type(inp) is dict:
                if 'name' in inp:
                    return inp['name']
                for i in inp:
                    ans = recursive_function(inp[i])
                    if ans != None:
                        return ans
            else:
                return None
        ans = recursive_function(inp)
        return ans if ans else "Could NOT find the new token tx"
        message.channel.send(price_of_gas(result.json()['operations'][0]['tokenInfo']['name']))
     
    
    class MyClient(discord.Client):
        async def on_ready(self):
            print('Logged on as', self.user)
      
        async def on_message(self, message):
            # don't respond to ourselves
            if message.author == self.user:
                return
            if message.content == '.get':
                #send message    
            #checking other commands like '.help'
            

    while True:
        # Code executed here
        print ('done')
        time.sleep(1)
    client = MyClient()
    client.run("mytoken")

当脚本检查时看起来像这样,如果输出令牌,然后程序在那里运行 .get 命令或类似的东西。我在这上面工作了 7 个小时,但我无法让它工作。

标签: pythonjsonapidiscorddiscord.py

解决方案


我认为你应该把它放在你的代码的顶部,因为(就像@effprime 说的)如果你的机器人在无限的while循环下,你的机器人永远不会在线:

import requests , time , json , sys , discord
result=requests.get('myapi')

result.json()
results = "soon:tm:"
client = MyClient()
client.run("mytoken")

要回答您的主要问题,即“如何每 30 秒运行一次脚本,然后发送 discrod msg”,我会编写一个类似的 while 循环:

while True:
    # Code executed here
    print ('Done')
    time.sleep(30) #you pause the code for 30 seconds everytime all the code as been executed.

推荐阅读