【问题标题】:Python If its same output dont send msgPython 如果它的相同输出不发送消息
【发布时间】:2021-04-21 20:13:01
【问题描述】:

我制作了一个 discord 机器人,它每 120 秒从一个以太坊地址发送 事务,但我不想一遍又一遍地发送相同的东西,所以如果它发送 USDT 令牌并在 120 秒内再次尝试 USDT 跳过它直到它有新的东西是可能的吗? 代码:

import requests
import sys 
import json
import discord
import time
btoken = "mytoken"
result=requests.get('https://api.ethplorer.io/getAddressHistory/0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be?apiKey=freekey&type=transfer')
result.status_code
result.text
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"
print (price_of_gas(result.json()))

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':
            await message.channel.send('Alert! Alert! Buy')
            await message.channel.send(result.json()['operations'][0]['tokenInfo']['symbol'])
            await message.channel.send(result.json()['operations'][0]['tokenInfo']['address'])
            
            print ('get command was tryed')
        else:
            print ('comand not found')
            
        if message.content == '.help':
            await message.channel.send("try .get")
            print ('help command was tryed')
        if message.content == '.stop':
           await message.channel.send('Bye...')
           print('bye') 
           sys.exit()
        if message.content == '.start':
         while True:
              # Code executed here
              print ('done')
              price_of_gas(result.json())
              print (price_of_gas(result.json()))
              await message.channel.send(price_of_gas(result.json())) 
              time.sleep(120)    

              
           
        
#print(result.json()['operations'][0]['tokenInfo']['name'])
#print(result.json()['operations'][0]['tokenInfo']['symbol'])
#print(result.json()['operations'][0]['tokenInfo']['address'])

#print (result.json()['tokenSymbol'])
#print (result.text)
print ('done no errors')

print ('done no errors with check data')
client = MyClient()
client.run(btoken)
   


        
              


print ('done no errors 2')

所以如果用户键入 .start 机器人将启动 while 循环,从选定的地址发送最新的 tx,但问题是它会发送相同的东西,我只需要一些 if 语句在 while 循环或其他东西。

【问题讨论】:

    标签: python json api bots discord.py


    【解决方案1】:
    1. 你不应该使用requests模块(它是阻塞的),你应该使用aiohttp来代替
    2. 你也不应该使用time.sleep,因为它也会阻塞整个线程。你应该使用asyncio.sleep。 (如果您仍然使用 time.sleep,您将无法在机器人“休眠”时使用它)

    回答您的问题,您可以简单地使用具有先前价格/值的值的变量并检查新消息是否相同,如果不是 - 发送它

    while True:
        price = price_of_gas(result.json())
        # Checking if the `previous_price` var exists
        if hasattr(self, "previous_price"): 
            # If yes, comparing the values
            if self.previous_price != price: 
                # If they're not the same, send the message
                await message.channel.send(f"Current price: {price}")
                self.previous_price = price # Updating the variable
    
        else:
            # If the `previous_price` var doesn't exists, creating it
            self.previous_price = price
    
        await asyncio.sleep(120) # Remember to import asyncio
    

    使用 aiohttp 发出 HTTP 请求

    import aiohttp
    
    async def main():
        async with aiohttp.ClientSession() as session:
            async with session.get("URL") as resp:
                data = await resp.json()
    
        # Note: you should create ONE session per application
    

    编辑:

    如果你想使用阻塞函数(比如price_of_gas)你可以使用下一个方法

    await self.loop.run_in_executor(None, price_of_gas, result.json())
    

    更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      相关资源
      最近更新 更多