shawnanastasio / python-matrix-bot-api

A Python API for making Matrix bots (https://matrix.org).
GNU General Public License v3.0
92 stars 34 forks source link

Using regex? #14

Closed n1ghthunt3r closed 5 years ago

n1ghthunt3r commented 5 years ago

I'm trying to use a regex in my code to only call my bot when user put an IP (so the bot check if this is valid or not) but I'm having problems to pass the variable to the regex. Anybody knows how to do it?

`import random import json import threading import re from urllib.request import urlopen from matrix_bot_api.matrix_bot_api import MatrixBotAPI from matrix_bot_api.mregex_handler import MRegexHandler from matrix_bot_api.mcommand_handler import MCommandHandler

Global variables

USERNAME = "ipornot" # Bot's username PASSWORD = "123456" # Bot's password SERVER = "server" # Matrix server URL

POSITIVE IP CALLBACK

def hi_callbackPositive(room, event): room.send_text("Hello, " + event['sender'] + " is a valid IP")

NEGATIVE IP CALLBACK

def hi_callbackNegative(room, event): room.send_text("Hello, " + event['sender'] + test + " is NOT a valid IP")

def echo_callback(room, event): args = event['content']['body'].split() args.pop(0)

# Echo what they said back
room.send_text(' '.join(args))

def main():

Create an instance of the MatrixBotAPI

bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER)

# Add a regex handler waiting for the word Hi
# THIS IS THE TRIGGER TO THE ANSWER
#call = "!"
trigger = " "
pat = re.compile("!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
test = pat.match(trigger)
if test:
    hi_handler = MRegexHandler(str(test), hi_callbackPositive)
    bot.add_handler(hi_handler)
else:
    hi_handler = MRegexHandler(str(test), hi_callbackNegative)
    bot.add_handler(hi_handler)

# Start polling
bot.start_polling()

# Infinitely read stdin to stall main thread while the bot runs in other threads
while True:
    input()

if name == "main": main()`