def main() -> int: """ Our main() function! :return: exit code :rtype: int """ log.info("Init MatrixBotAPI...") try: bot = MatrixBotAPI(config.USERNAME, config.PASSWORD, config.SERVER) register_bot_callbacks(bot) bot.start_polling() log.info("...success, started polling!") except: log.critical("...failure!\nDetails:\n", exc_info=1) return EXIT_MATRIX_API log.info("Suspending MainThread") while True: try: time.sleep(2.628e+6) # Approximately 1 month... except SystemExit: return EXIT_SUCCESS log.info("A month passed, lol~")
def register_bot_callbacks(bot: MatrixBotAPI): """ Define all handlers and register callbacks. :param MatrixBotAPI bot: bot instance """ bot.add_handler(MCommandHandler('meh', bot_cmd_meh)) bot.add_handler(MCommandHandler('fug', bot_cmd_fug)) bot.add_handler(MCommandHandler('трави', bot_cmd_bashorg))
def main(): # Load configuration config = configparser.ConfigParser() config.read("config.ini") username = config.get("Matrix", "Username") password = config.get("Matrix", "Password") server = config.get("Matrix", "Homeserver") # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(username, password, server) # Add a regex handler waiting for the echo command dish_handler = MCommandHandler("dish", dish_points_callback) bot.add_handler(dish_handler) help_handler = MCommandHandler("pointshelp", points_help_callback) bot.add_handler(help_handler) # Start polling bot.start_polling() # Infinitely read stdin to stall main thread while the bot runs in other threads while True: input()
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) member_handler = MMemberHandler(member_callback) bot.add_handler(member_handler) faq_handler = MCommandHandler("faq", faq_callback) bot.add_handler(faq_handler) faq1_handler = MCommandHandler("фаг", faq_callback) bot.add_handler(faq1_handler) bot.start_polling() while True: input()
def __init__(self, server, username, password): # This is a bit broken. We don't want to hardcode any room, so set this as soon as we get the first message. # The bot is talking to that room then self.primary_room = None self.receive_handler = None self.reset_handler = None self.bot = MatrixBotAPI(username, password, server.rstrip("/")) # Add a regex handler for every message msg_handler = MRegexHandler("^(?!\\!).+", self.__msg_callback) self.bot.add_handler(msg_handler) reset_handler = MCommandHandler("reset", self.__reset_callback) self.bot.add_handler(reset_handler) preset_handler = MCommandHandler("preset", self.__preset_callback) self.bot.add_handler(preset_handler) self.bot.start_polling()
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) #botModules.LoadClasses("H:\Programming\PythonStuff\Jarvis\Components") componentFolderPath = os.path.join(script_dir, COMPONENTSFOLDER) botModules.LoadClasses( componentFolderPath, componentFolderPath ) #give path to Components folder and path to Component config folder botModules.CallMethodOnAll( "Start") # Call start function on all loaded components componentHandler = MComponentHandler(component_callback) bot.add_handler( componentHandler ) # adds component handler that deals with call events at correct time for all components #ignoreUser_handler = MCommandHandler("ignoreUser", IgnoreUser_callback) #bot.add_handler(ignoreUser_handler) # Start polling bot.start_polling() # Infinitely read stdin to stall main thread while the bot runs in other threads go = True while go: botModules.CallMethodOnAll("Update") go = True
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) # Add a regex handler waiting for the word Hi hi_handler = MRegexHandler("Hi", hi_callback) bot.add_handler(hi_handler) # Add a regex handler waiting for the echo command echo_handler = MCommandHandler("echo", echo_callback) bot.add_handler(echo_handler) # Add a regex handler waiting for the die roll command dieroll_handler = MCommandHandler("d", dieroll_callback) bot.add_handler(dieroll_handler) # Start polling bot.start_polling() # Infinitely read stdin to stall main thread while the bot runs in other threads while True: input()
def main(): """Main function. """ zabbix.logging = logging matrix.logging = logging config['config'] = args['config'] # Create an instance of the MatrixBotAPI homeserver = "https://{server}:{port}".format( server=matrix_config['homeserver'], port=int(matrix_config['port'])) rooms = list(config['zabbix-bot'].keys()) token = None username = matrix_config['username'] if 'token' in matrix_config: token = matrix_config['token'] username = matrix_config['user_id'] bot = MatrixBotAPI( username, matrix_config['password'], homeserver, rooms=rooms, token=token, ) # Add a !zabbix handler zabbix_handler = MRegexHandler("^!zabbix", zabbix_callback) bot.add_handler(zabbix_handler) # Start polling while True: thread = bot.start_polling() thread.join() logging.warning( 'thread died, waiting five seconds before connecting again...') time.sleep(5)
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(Config.BOT_USER_NAME, Config.BOT_PASS_WORD, Config.BOT_SERVER_URL) # Add a regex handler waiting for the user text bot.add_handler(MRegexHandler(".*", echo_callback)) # Start polling bot.start_polling() # Infinitely read stdin to stall main thread while the bot runs in other threads while True: input()
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) # Add a regex handler waiting for the ! symbol at the beginning of the # message. tick_handler = MRegexHandler("^!.*", tick_callback) bot.add_handler(tick_handler) # Start polling. bot.start_polling() # Infinite sleep while the bot runs in other threads. while True: time.sleep(1)
def main(): # Create an instance of the MatrixBotAPI logging.debug('matrix config:\n%s', matrix_config) homeserver = "https://{server}:{port}".format( server=matrix_config['homeserver'], port=int(matrix_config['port'])) bot = MatrixBotAPI(matrix_config['username'], matrix_config['password'], homeserver) # Add a !zabbix handler zabbix_handler = MRegexHandler("^!zabbix", zabbix_callback) bot.add_handler(zabbix_handler) # Add a !dnsjedi handler dnsjedi_handler = MRegexHandler("^!dnsjedi", dnsjedi_callback) bot.add_handler(dnsjedi_handler) # Start polling while True: thread = bot.start_polling() thread.join() logging.warning( 'thread died, waiting five seconds before connecting again...') time.sleep(5)
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) # Set avatar / fix this later # bot.set_matrix_avatar(AVATAR_URL) # Hello testing handler hello_handler = MCommandHandler("hello", hello_callback) bot.add_handler(hello_handler) # Host inspection handler hi_handler = MCommandHandler("hi", hi_callback) bot.add_handler(hi_handler) # Subdomain inspection handler si_handler = MCommandHandler("si", si_callback) bot.add_handler(si_handler) # Help handler help_handler = MCommandHandler("helpmonty", help_callback) bot.add_handler(help_handler) # POST handler post_handler = MCommandHandler("post", post_callback) bot.add_handler(post_handler) # Start polling bot.start_polling() # Infinitely read stdin to stall main thread while the bot runs in other threads while True: input()
from bs4 import BeautifulSoup from matrix_bot_api.matrix_bot_api import MatrixBotAPI from matrix_bot_api.mregex_handler import MRegexHandler from mistune import markdown from api_selenium import UmsConnection from models import User, Profile, CurrentProfile from utils import have_access, send_exception config = configparser.ConfigParser() config.read('config.ini') bot_username = config.get('Bot', 'username') bot_password = config.get('Bot', 'password') server_url = config.get('Bot', 'server_url') BOT = MatrixBotAPI(bot_username, bot_password, server_url) # [(Profile, UmsConnection), ] CONNECTIONS = [] with open('whitelist_users.txt') as f: whitelist = [i.strip() for i in f] private_access = have_access(usernames=whitelist) # TODO декоратор is_authorized markdown = partial(markdown, hard_wrap=True) with open('bot_help.md', 'r') as f: HELP = markdown(f.read())
def main(): # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) for x in dict(config.items("TEXT_COMMANDS")): text_handler = MCommandHandler(x, text_callback) bot.add_handler(text_handler) photo_handler = MCommandHandler("photo", photo_callback) bot.add_handler(photo_handler) reinit_handler = MCommandHandler("reinit", reinit) bot.add_handler(reinit_handler) helpfile_handler = MCommandHandler("help", helpfile_callback) bot.add_handler(helpfile_handler) # Start polling bot.start_polling() print("Polling started") while True: input()
def run_bot(modules): global bot # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(os.environ['MATRIX_USERNAME'], os.environ['MATRIX_PASSWORD'], os.environ['MATRIX_SERVER']) # Add some helper functions: # Sends a message to notifyroom def send_notification(self, notification, notifyroom): room = self.get_room(notifyroom) room.send_text(notification) # Lookup room object for room id. Bot must be present in room. def get_room(self, room_id): print('Looking up room ', room_id, '...') for id, room in bot.client.get_rooms().items(): if room_id in room.aliases: return room print('Error finding room', room_id, ' - is bot present on it?') bot.send_notification = types.MethodType(send_notification, bot) bot.get_room = types.MethodType(get_room, bot) # Add a handler waiting for any command modular_handler = MCommandHandler("", modular_callback) bot.add_handler(modular_handler) # Store modules in bot to be accessible from other modules bot.modules = modules print('Starting modules..') # Call matrix_start on each module for modulename, moduleobject in modules.items(): if "matrix_start" in dir(moduleobject): try: moduleobject.matrix_start(bot) except: traceback.print_exc(file=sys.stderr) # Start polling bot.start_polling() bot.running = True signal.signal(signal.SIGINT, signal_handler) print('Bot running, press Ctrl-C to quit..') # Wait until ctrl-c is pressed pollcount = 0 while bot.running: for modulename, moduleobject in modules.items(): if "matrix_poll" in dir(moduleobject): try: moduleobject.matrix_poll(bot, pollcount) except: traceback.print_exc(file=sys.stderr) time.sleep(10) pollcount = pollcount + 1 # Call matrix_stop on each module for modulename, moduleobject in modules.items(): if "matrix_stop" in dir(moduleobject): try: moduleobject.matrix_stop(bot) except: traceback.print_exc(file=sys.stderr)
def main(): # Load configuration config = configparser.ConfigParser() config.read("config.ini") username = config.get("Matrix", "Username") password = config.get("Matrix", "Password") server = config.get("Matrix", "Homeserver") # Start bot bot = MatrixBotAPI(username, password, server) m_newpoll_handler = MCommandHandler('newpoll', newpoll_callback) bot.add_handler(m_newpoll_handler) m_ongoing_poll_handler = AllMessageHandler(ongoing_poll_callback) bot.add_handler(m_ongoing_poll_handler) m_startpoll_handler = MCommandHandler('startpoll', startpoll_callback) bot.add_handler(m_startpoll_handler) m_info_handler = MCommandHandler('info', info_callback) bot.add_handler(m_info_handler) m_endpoll_handler = MCommandHandler('endpoll', endpoll_callback) bot.add_handler(m_endpoll_handler) m_results_handler = MCommandHandler('results', results_callback) bot.add_handler(m_results_handler) m_vote_handler = MCommandHandler('vote', vote_callback) bot.add_handler(m_vote_handler) m_pollhelp_handler = MCommandHandler('pollhelp', pollhelp_callback) bot.add_handler(m_pollhelp_handler) bot.start_polling() print("Pollbot started!") def sig_handle(signo, frame): global BOT_CONT print ("Gracefully shutting down") BOT_CONT = False signal.signal(signal.SIGINT, sig_handle) while BOT_CONT: signal.pause()
class BottyMcBotface: def __init__(self, server, username, password): # This is a bit broken. We don't want to hardcode any room, so set this as soon as we get the first message. # The bot is talking to that room then self.primary_room = None self.receive_handler = None self.reset_handler = None self.bot = MatrixBotAPI(username, password, server.rstrip("/")) # Add a regex handler for every message msg_handler = MRegexHandler("^(?!\\!).+", self.__msg_callback) self.bot.add_handler(msg_handler) reset_handler = MCommandHandler("reset", self.__reset_callback) self.bot.add_handler(reset_handler) preset_handler = MCommandHandler("preset", self.__preset_callback) self.bot.add_handler(preset_handler) self.bot.start_polling() def __set_primary_room(self, room): if self.primary_room is None: print("Primary room set!") print(room) self.primary_room = room def __msg_callback(self, room, event): self.__set_primary_room(room) if self.receive_handler is not None: if event["type"] == "m.room.message" and event["content"][ "msgtype"] == "m.text": self.receive_handler(room, event["sender"], event["content"]["body"]) def __reset_callback(self, room, event): self.__set_primary_room(room) print("Reset!") if self.reset_handler is not None: self.reset_handler(event["sender"], False) def __preset_callback(self, room, event): self.__set_primary_room(room) print("Preference reset!") if self.reset_handler is not None: self.reset_handler(event["sender"], True) def set_reset_handler(self, handler): self.reset_handler = handler def set_receive_handler(self, handler): self.receive_handler = handler def send(self, message, handle=None): if self.primary_room is None: raise Exception("no room set, write a message to set the room") if handle is None: self.primary_room.send_text("{}".format(message)) else: self.primary_room.send_text("{} {}".format(handle, message))
def alsobot_test_callback(room, event): server = MinecraftServer(MINECRAFTSERVERNAME) status = server.status() info_string = "The server has {0} players and replied in {1} ms".format( status.players.online, status.latency) room.send_text(info_string) if __name__ == '__main__': USERNAME = os.getenv('ALSOBOTUSER', "") PASSWORD = os.getenv('ALSOBOTPASSWORD', "") SERVER = os.getenv('ALSOBOTSERVER', "") MINECRAFTSERVER = os.getenv('ALSOBOTMINECRAFTSERVER', "") if (USERNAME or PASSWORD or SERVER or ALSOBOTMINECRAFTSERVER) == "": #print("{} {} {}".format(USERNAME, PASSWORD, SERVER)) print( "Set ALSOBOTUSER, ALSOBOTPASSWORD, ALSOBOTSERVER, or ALSOBOTMINECRAFTSERVER environment variables!" ) sys.exit() matrix_bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) alsobot = Alsobot(MINECRAFTSERVER) alsobot_test_handler = MRegexHandler("alsobot", alsobot.default_response) matrix_bot.add_handler(alsobot_test_handler) matrix_bot.start_polling() while True: input()
def main(): global bot # Load configuration config = configparser.ConfigParser() config.read("config.ini") username = config.get("Matrix", "Username") password = config.get("Matrix", "Password") server = config.get("Matrix", "Homeserver") # Start bot bot = MatrixBotAPI(username, password, server) m_newpoll_handler = MCommandHandler('newpoll', newpoll_callback) bot.add_handler(m_newpoll_handler) m_ongoing_poll_handler = AllMessageHandler(ongoing_poll_callback) bot.add_handler(m_ongoing_poll_handler) m_startpoll_handler = MCommandHandler('startpoll', startpoll_callback) bot.add_handler(m_startpoll_handler) m_add_response_handler = MCommandHandler('add', add_response_to_poll) bot.add_handler(m_add_response_handler) m_info_handler = MCommandHandler('info', info_callback) bot.add_handler(m_info_handler) m_endpoll_handler = MCommandHandler('endpoll', endpoll_callback) bot.add_handler(m_endpoll_handler) m_results_handler = MCommandHandler('results', results_callback) bot.add_handler(m_results_handler) m_vote_handler = MCommandHandler('vote', vote_callback) bot.add_handler(m_vote_handler) m_pollhelp_handler = MCommandHandler('pollhelp', pollhelp_callback) bot.add_handler(m_pollhelp_handler) m_leave_handler = MCommandHandler('leave', leave_callback) bot.add_handler(m_leave_handler) bot.start_polling() print("Pollbot started!") while True: try: input() except EOFError: print("EOF access")
def main(): # Load configuration config = configparser.ConfigParser() config.read("config.ini") username = config.get("Matrix", "Username") password = config.get("Matrix", "Password") server = config.get("Matrix", "Homeserver") # Start bot bot = MatrixBotAPI(username, password, server) m_newmotion_handler = MCommandHandler('motion', newmotion_callback) bot.add_handler(m_newmotion_handler) m_ongoing_motion_handler = AllMessageHandler(ongoing_motion_callback) bot.add_handler(m_ongoing_motion_handler) m_startmotion_handler = MCommandHandler('startmotion', startmotion_callback) bot.add_handler(m_startmotion_handler) m_info_handler = MCommandHandler('info', info_callback) bot.add_handler(m_info_handler) m_endmotion_handler = MCommandHandler('endmotion', endmotion_callback) bot.add_handler(m_endmotion_handler) m_results_handler = MCommandHandler('results', results_callback) bot.add_handler(m_results_handler) m_vote_handler = MCommandHandler('vote', vote_callback) bot.add_handler(m_vote_handler) m_motionhelp_handler = MCommandHandler('motionhelp', motionhelp_callback) bot.add_handler(m_motionhelp_handler) bot.start_polling() print("Motionbot started!") while True: input()
def main(): configfp = open('config.json') cfg = json.load(configfp) USERNAME, PASSWORD, SERVER = cfg["username"], cfg["password"], cfg[ "server"] # Create an instance of the MatrixBotAPI bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER) hottopic_handler = MCommandHandler("hottopics", hottopic_callback) bot.add_handler(hottopic_handler) pins_handler = MCommandHandler("pins", pins_callback) bot.add_handler(pins_handler) lcpu_event_handler = MCommandHandler("event", lcpu_event_callback) bot.add_handler(lcpu_event_handler) bot.add_handler(MCommandHandler("readpost", readpost_callback)) # Start polling bot.start_polling() # Infinitely read stdin to stall main thread while the bot runs in other # threads while True: sleep(600) rooms = bot.client.get_rooms().values() do_timer_events(rooms)