Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Wanting to pass data from one script to another while they are both running

So I'm making a Discord Bot that posts when a person goes live on Twitch.tv. At the moment I have a Python program that runs the bot and a program that runs a mini server to receive the data from the Twitch server(webhook). I am unsure on how to pass on the data I receive from my server to the discord bot. Both programs have to be running at the same time.

DiscordBot

import discord


client = discord.Client()




async def goes_live(data):
    print(data)
    print('Going Live')
    msg = '--- has gone live'
    await client.send_message(discord.Object(id='---'), msg)


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    message.content = message.content.casefold()


@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')


client.run('---')

Web server

import web

urls = ('/.*', 'hooks')

app = web.application(urls, globals())


class hooks:

    def POST(self):
        data = web.data()
        print("")
        print('DATA RECEIVED:')
        print(data)
        print("")

        return 'OK'

    def GET(self):
        try:
            data = web.input()
            data = data['hub.challenge']
            print("Hub challenge: ", data)
            return data
        except KeyError:
            return web.BadRequest



if __name__ == '__main__':
    app.run()
like image 744
Masonator Avatar asked Oct 17 '22 13:10

Masonator


1 Answers

Since both your programs are in python, and if they are related to each other enough that they always run together, you can simply use multiprocessing module: have each one of the programs run as a multiprocessing.Process instance, and give each one of them one end of a multiprocessing.Pipe, that way you can exchange informations between processes.

The architecture would look something like that main.py:

# main.py
from multiprocessing import Process, Pipe
import program_1
import program_2

program_1_pipe_end, program_2_pipe_end = Pipe()

process_1 = Process(
    target = program_1.main,
    args = (program_1_pipe_end,)
    )

process_2 = Process(
    target = program_2.main,
    args = (program_2_pipe_end,)
    )

process_1.start()
process_2.start()
#Now they are running
process_1.join()
process_2.join()
# program_1.py and program_2.py follow this model

# [...]

# instead of if __name__ == '__main__' , do:
def main(pipe_end):
    # and use that pipe end to discuss with the other program
    pass

You can find the Pipe documentation here, (inside multiprocessing documentation).

like image 93
Jenny Avatar answered Oct 20 '22 23:10

Jenny