Will Pile Will Pile - 14 days ago 8
Python Question

Trying to call functions based on IRC user input

I'm fairly new to Python, but not new to programming. Basically, I'm trying to call certain functions/procedures to simulate keyboard/mouse based on user input from an IRC channel.

I am running an IRC bot on twitch like a twitch plays sort of thing. I know how to simulate keyboard and mouse input, but I'm having trouble figuring out how to do this efficiently.

I have a class for the bot and it starts like:

class bot:
def __init__(self):
...
login stuff
...
self.options = {'!test': self.command_test,
'q': self.quickSave,
'f': self.forward,
'ff': self.forward2,
'fff': self.forward3
}
...


and then the functions are called while the bot parses IRC chat input like so:

def parse_message(self, msg):
if len(msg) >= 1:
msg = msg.split(' ')
if msg[0] in self.options:
self.options[msg[0]]()


I have a load of functions that are basically the same only repeated. (forward, forward2, forward3, left, left2, left3, etc). It really makes no sense to repeat the same function over and over. I cannot figure out how to efficiently call these functions like forward(1), forward(2), forward(3), etc.

I would like my code to look like this:

def forward(self, num):
for x in range(1, num):
#Simulate walking forward


I just cant figure out how to add arguments to forward() using simple text input. This is hard for me to explain, just imagine a hundred people voting to move/aim in a video game in an IRC channel.

Again, I'm not asking for help emulating mouse/keyboard input. I just need advice about how to use text to call functions.

if it help you understand, i'm attempting to croudplay fallout 4

Answer

So, each command is actually one symbol, and repeating a symbol n times means calling the associated function the same amount of times, right?

Assuming command is a string of symbols without spaces, it could be done like that:

command = #get command

for char in command:
    your_dict[char]()

BTW, it's not really needed to check whether the dictionary contains the specified command. Just wrap the calling into a try/except block:

try
   your_dict[char]()
except KeyError:
    # this is OK, tell the user that it's an error
except:
    # this means that some of the functions has raised an error
Comments