如何与另一个函数异步使用discord.py

发布于 2025-01-12 01:15:20 字数 3058 浏览 3 评论 0原文

我正在尝试以在启动时运行函数 background() 的方式运行此代码,同时还运行 client.run() 来启动不和谐机器人。我怎样才能实现这个目标?在当前状态下,根据我调用上述函数的顺序,它只运行第一个函数,因此在这种情况下,它只运行不和谐机器人,因为我首先调用了该函数......

from hashlib import new
from re import I
from web3 import Web3
import sys, json, time, asyncio, threading
from logging import exception
import json
import time
import urllib3
import discord
from discord.ext.commands import Bot
from discord.ext import commands

# set rpc
web3 = Web3(Web3.HTTPProvider("rpc goes here (i have hidden for this post)"))

# use https://github.com/Cog-Creators/Red-DiscordBot/issues/581 to solve SSL problems on Mac OS
# use "token" not "client secret" for discord bot
discord_token = ('discord secret here i have hidden for this post')
# init discord stuff
client = discord.Client()
# set bot command prefix
client = commands.Bot(command_prefix = '$') #put your own prefix here


# take block data input, parse for new contract, then call discord function to broadcast
async def contractTx(txhash):
    # call when new block is found to get contract addy and send it to discord
    new_contract = web3.eth.get_transaction_receipt(txhash)
    global contract_address
    contract_address = new_contract['contractAddress']
    print(f"New contract deployed: {contract_address}")
    await new_contract_discord(contract_address=contract_address)



# runs on program startup
async def background():
    # set block index
    global block_index
    block_index = web3.eth.get_block_number()
    # start looping through blocks
    while True:
        if block_index != web3.eth.get_block_number():
            # new block, do the things
            # set current block to new block
            block_index = web3.eth.get_block_number()
            # check if transactions in new block contain new contract creation
            # if yes, send to main function
            print(f"NEW BLOCK: {block_index}")
            global transactions
            current_block = web3.eth.get_block(block_index, full_transactions=True)
            transactions = current_block.transactions
            for tx in transactions:
                if tx['to'] != None:
                    # is a contract creation tx, send to export function
                    task1 = asyncio.create_task(contractTx(tx['hash'].hex()))
        else:
            # still the same block, so wait a bit
            print("no new blocks")
            await asyncio.sleep(1)



@client.event
async def on_ready():
    print("bot online") #will print "bot online" in the console when the bot is online

@client.event
async def new_contract_discord(ctx, contract_address):
    channel = client.get_channel(949889447938367531)
    await channel.send(f"new contract: {contract_address}")


# test command so you know how it works
# do $foo "string" and it responds with "string"
@client.command()
async def foo(ctx, arg):
    await ctx.send(arg)

# run the discord bot with the token
client.run(discord_token)

# run the background func
asyncio.run(background())```

I am trying to run this code in a way that runs the function background() at startup while also running client.run() to start a discord bot. How can I achieve this? In its current state, depending on which order I call the functions mentioned above, it only runs the first one, so in this case it only runs the discord bot because i called the function first...

from hashlib import new
from re import I
from web3 import Web3
import sys, json, time, asyncio, threading
from logging import exception
import json
import time
import urllib3
import discord
from discord.ext.commands import Bot
from discord.ext import commands

# set rpc
web3 = Web3(Web3.HTTPProvider("rpc goes here (i have hidden for this post)"))

# use https://github.com/Cog-Creators/Red-DiscordBot/issues/581 to solve SSL problems on Mac OS
# use "token" not "client secret" for discord bot
discord_token = ('discord secret here i have hidden for this post')
# init discord stuff
client = discord.Client()
# set bot command prefix
client = commands.Bot(command_prefix = '
) #put your own prefix here


# take block data input, parse for new contract, then call discord function to broadcast
async def contractTx(txhash):
    # call when new block is found to get contract addy and send it to discord
    new_contract = web3.eth.get_transaction_receipt(txhash)
    global contract_address
    contract_address = new_contract['contractAddress']
    print(f"New contract deployed: {contract_address}")
    await new_contract_discord(contract_address=contract_address)



# runs on program startup
async def background():
    # set block index
    global block_index
    block_index = web3.eth.get_block_number()
    # start looping through blocks
    while True:
        if block_index != web3.eth.get_block_number():
            # new block, do the things
            # set current block to new block
            block_index = web3.eth.get_block_number()
            # check if transactions in new block contain new contract creation
            # if yes, send to main function
            print(f"NEW BLOCK: {block_index}")
            global transactions
            current_block = web3.eth.get_block(block_index, full_transactions=True)
            transactions = current_block.transactions
            for tx in transactions:
                if tx['to'] != None:
                    # is a contract creation tx, send to export function
                    task1 = asyncio.create_task(contractTx(tx['hash'].hex()))
        else:
            # still the same block, so wait a bit
            print("no new blocks")
            await asyncio.sleep(1)



@client.event
async def on_ready():
    print("bot online") #will print "bot online" in the console when the bot is online

@client.event
async def new_contract_discord(ctx, contract_address):
    channel = client.get_channel(949889447938367531)
    await channel.send(f"new contract: {contract_address}")


# test command so you know how it works
# do $foo "string" and it responds with "string"
@client.command()
async def foo(ctx, arg):
    await ctx.send(arg)

# run the discord bot with the token
client.run(discord_token)

# run the background func
asyncio.run(background())```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠北森屋 2025-01-19 01:15:20
import threading
def A():
    while True:
        print("A")
def B():
    while True:
        print("B")
threading.Thread(target=A).start()
threading.Thread(target=B).start()

这将输出 ABABAB... 因此,这些功能是同时运行的。

import threading
def A():
    while True:
        print("A")
def B():
    while True:
        print("B")
threading.Thread(target=A).start()
threading.Thread(target=B).start()

This will output ABABAB... So, the functions are running simultaneously.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文