John Warts
John Warts

Reputation: 34

How to use discord.py asynchronously with another function

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())```

Upvotes: 1

Views: 1440

Answers (1)

user17780528
user17780528

Reputation:

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.

Upvotes: 2

Related Questions