def main(): print "init..." yuki = bot() print "connecting..." yuki.connect() print "auth..." yuki.auth() #TODO:Это и начальный статус пренести в отдельную функцию start или как-то там #Устанавливаем функцию-обработчик сообщений yuki.client.RegisterHandler('message', yuki.process_message) yuki.client.RegisterDisconnectHandler(yuki.process_disconnect) yuki.client.RegisterHandler('presence', yuki.process_presence) yuki.client.sendInitPresence() #TODO: Создать функцию подключения к конференции room = "[email protected]/yuki" print "Joining " + room presence = xmpp.Presence(to=room) #Закомментированная строка нужна для подключения к конференциям с паролем. #presence.setTag('x',namespace=xmpp.NS_MUC).setTagData('password','helloandwelcome') yuki.client.send(presence) #Начальный статус yuki.set_status(u"available",u"Привет, мир!") # Main cycle while yuki.running == True: yuki.client.Process(1) print u"Отключаемся..." yuki.disconnect() print u"Выходим..." sys.exit(0)
def main(): irc = twitchchat("drluke4", "oauth:vb6vffy4rqtvon9izfi928g3yoytd1", "#drluke4") uguu = bot(irc) pri = printer(uguu) irc.addcommand(uguu.drawmatrixcallback, "draw") irc.addcommand(uguu.helpcallback, "help") irc.addcommand(uguu.drawhexcallback, "hex") while(1): irc.parse(bytes.decode(irc.recv())) if(not irc.valid): irc = twitchchat("drluke4", "oauth:vb6vffy4rqtvon9izfi928g3yoytd1", "#drluke4") pri.work()
def __init__(self, jid_passwords, whitelist): """ Initialize a hexchat XMPP bot. Also connect to the XMPP server. 'jid' is the login username@chatserver 'password' is the password to login with """ #whitelist of trusted ip addresses client sockets can connect to #if None, can connect to anything self.whitelist=whitelist # <local_address> => <listening_socket> dictionary, # where 'local_address' is an IP:PORT string with the locallistening address, # and 'listening_socket' is the socket that listens and accepts connections on that address. self.server_sockets={} # <connection_id> => <xmpp_socket> dictionary, # where 'connection_id' is a tuple of the form: # (bound ip:port on client, xmpp username of server, ip:port server should forward data to) # and 'xmpp_socket' is a sleekxmpp socket that speaks to the XMPP bot on the other side. self.client_sockets={} #pending connections self.pending_connections={} #peer's resources self.peer_resources={} #locks self.client_sockets_lock=threading.Lock() self.pending_connections_lock=threading.Lock() self.peer_resources_lock=threading.Lock() self.bot_lock=threading.Lock() #initialize the other sleekxmpp clients. self.bots=[] for jid_password in jid_passwords: self.bots.append(bot(self, jid_password)) self.bot_index=0 while True in map(lambda bot: bot.boundjid.full==bot.boundjid.bare, self.bots): time.sleep(0.5) self.aliases=frozenset(map(lambda bot: bot.boundjid.full, self.bots)) for index in range(len(self.bots)): self.bots[index].register_hexchat_handlers()
def on_send_message(data): """recieve message, parse, add to db, and update messages""" date = datetime.now(TIME_ZONE) msg = msg_parser.parse_pictures_and_links(data['message']) #add message to db db.session.add( models.Messages(clients[data['id']]['name'], msg, date.strftime("%H:%M %m/%d/%y"))) db.session.commit() #add message to this instance's data storage messages.append({ 'user': clients[data['id']]['name'], 'message': msg, 'timestamp': date.strftime("%H:%M %m/%d/%y") }) #Check if message is a command if data['message'][:2] == '!!': #respond with bot data['user'] = '******' data['message'] = bot(data['message']) #add bot message to db db.session.add( models.Messages(data['user'], data['message'], date.strftime("%H:%M %m/%d/%y"))) db.session.commit() #add bot message to this instance's data storage messages.append({ 'user': data['user'], 'message': data['message'], 'timestamp': date.strftime("%H:%M %m/%d/%y") }) #send all messages in storage to all users return socketio.emit('messages updated', {'messages': messages}, broadcast=True)
def main(): """ Main loop. """ username = input("Enter a username: "******"Enter a password: "******"Enter user to follow: ") message = input("Enter message to reply with: ") stalkerBot = bot.bot(username, password, stalk, message) try: while (True): print('Press CTRL + C to quit') # Works when ran from command line. stalkerBot.populateCheck() stalkerBot.setReplyCounter() stalkerBot.run() stalkerBot.writeCheck() stalkerBot.writeReplyCounter() print(stalkerBot.check) # Console Feedback of check list. stalkerBot.clearCheck() time.sleep(180) # Wait 3 minutes. except KeyboardInterrupt: pass
Player1 = Player( True, [ white_king, white_queen, white_rook_1, white_rook_2, white_bishop_1, white_bishop_2, white_knight_1, white_knight_2, ] + white_pawn, True, ) Player2 = bot( False, [ black_king, black_queen, black_rook_1, black_rook_2, black_bishop_1, black_bishop_2, black_knight_1, black_knight_2, ] + black_pawn, True, )
# Load commands.ini print('==> Loading commands') cmd = twitchcommands.commands() # Check if we have generated a default commands.ini, if so exit if cmd.default == True: print( '[!] Could not find command.ini. A default command.ini has been generated in the bot folder response. Please edit it and run the bot again.' ) sys.exit() # Ini files are valid, create a bot instance print('==> Connecting to Twitch IRC server') bot = udpbot.bot(conf.config['auth']['host'], int(conf.config['auth']['port']), conf.config['auth']['username'], conf.config['auth']['password'], conf.config['auth']['channel'], int(conf.config['auth']['timeout'])) # Connect to IRC server if bot.connect() == False: print( '[!] Connection error response. Please check your internet connection and config.ini file' ) sys.exit() # Send login packets print('==> Logging in') bot.login() # Check login errors
def do_hello(): input_text = request.forms.input_text output_text = bot(input_text) return template('bot_template', input_text=input_text, output_text=output_text)
from bot import bot import random import time import os import sys from ambiente import ambiente from tabelas import tabela_ambiente, tabela_tarefas from _global import insert_message, print_messages from estado_atmosferico import estado_atmosferico_normal, estado_atmosferico_frio, estado_atmosferico_quente ambiente = ambiente() TEMPO_GLOBAL = 0 intervalo_prints = 0.05 ambiente.estado_atmosferico = 'Normal' bot_decisao = bot() tabela_ambiente = tabela_ambiente(ambiente) tabela_tarefas = tabela_tarefas( bot_decisao.controlador.escalonador.tarefas_lista) event_flag = False while (True): time.sleep(intervalo_prints) if (TEMPO_GLOBAL % 600 == 0 or event_flag): if (event_flag): time.sleep(0.7) event_flag = False os.system('clear')
# main.py # Christopher O'Neal # # Main loader program for IRC bot # import time from bot import bot if __name__ == '__main__': bot = bot() try: bot.connect() bot.flush() bot.mainloop() except: print "Interrupt" bot.disconnect() raise
#Section 1: Variable network = 'irc.nullstorm.r00t.la' port = 6667 channels = ["#aubcom", "#nullstorm", "#aubcom-dnd"] channel = "#aubcom" # primary channel for !j and !p nick = "dicey" chars = {} hp = {} CharPickleFile = "chars.pickle" HPPickleFile = "hp.pickle" # Init the bot module. irc = bot.bot(master="dushkin", channels=channels, nick=nick) #Section 2: Functions def TextEval(txt): # Evaluates text as math expression return float(eval(txt, {"__builtins__": None}, safe_dict)) def Modifier(a): return math.floor((a - 10) / 2) def findKey(dic, val): for a in dic.items():
if (i < len(sys.argv) - 1): #read flags that takes input (cannot be last item in argv) if arg == '-c': flags[PARAM_CONFIG_FILENAME] = sys.argv[i + 1] continue start = True while (start): # Initialise requirements settings.init(flags) # read trading config config = configparser.RawConfigParser() config.read('./TradingConfig/' + flags[PARAM_CONFIG_FILENAME] + '.ini') tradingConfig = dict(config.items(PARAM_CONFIG_KEY)) walletConfig = dict(config.items(PARAM_CONFIG_PAPER_WALLET)) paperWallet = walletConfig['balance'] jsonWallet = json.loads(paperWallet) #init wallet wallet = Wallet(flags[PARM_IS_PAPER_TRADE], jsonWallet, flags[PARAM_CONFIG_FILENAME]) #bot btcBot = bot(symbol=flags[PARAM_CONFIG_FILENAME], wallet=wallet, flags=flags) print("Start.") start = btcBot.start()
from bot import bot from network_control import network_control from browser_control import browser_control from telegram_interaction import telegram_worker bot = bot(network_control=network_control, browser_control=browser_control, telegram_worker=telegram_worker) bot.run()
def __init__(self, jid_passwords, whitelist=None, num_logins=1, sequential_bootup=False, take_measurements=False): """ Initialize a hexchat XMPP bot. Also connect to the XMPP server. 'jid' is the login username@chatserver 'password' is the password to login with *jid_passwords contain tuples of the form (jid, password) *whitelist contains a list of ip:ports that we are allowed to connect to *num_logins is the number of times to login with a given JID *sequential_bootup determines whether to log into each account sequentially or concurrently """ #whitelist of trusted ip addresses client sockets can connect to #if None, can connect to anything self.whitelist = whitelist # <local_address> => <listening_socket> dictionary, # where 'local_address' is an IP:PORT string with the locallistening address, # and 'listening_socket' is the socket that listens and accepts connections on that address. self.server_sockets = {} # <connection_id> => <xmpp_socket> dictionary, # where 'connection_id' is a tuple of the form: # (bound ip:port on client, xmpp username of server, ip:port server should forward data to) # and 'xmpp_socket' is a sleekxmpp socket that speaks to the XMPP bot on the other side. self.client_sockets = {} # pending connections self.pending_connections = {} # disconnects that go out when a resource is unavailable # maps key => set of recipient aliases to use for sending disconnects self.pending_disconnects = {} # peer's resources self.peer_resources = Peer_Resource_DB() # for multiple logins self.connection_requests = {} # number of times to login to each account self.num_logins = num_logins # maps sockets to keys of client_sockets self.socket_map = {} # locks self.client_sockets_lock = threading.Lock() self.pending_connections_lock = threading.Lock() self.peer_resources_lock = threading.Lock() self.connection_requests_lock = threading.Lock() self.pending_disconnects_lock = threading.Lock() # initialize the sleekxmpp bots. self.bots = [] for login_num in range(self.num_logins): for jid_password in jid_passwords: bot0 = bot(self, jid_password) if sequential_bootup: bot0.boot() else: threading.Thread( name="booting %d %d" % (hash(jid_password), login_num), target=lambda: bot0.boot() ).start() self.bots.append(bot0) while False in map(lambda bot: bot.session_started_event.is_set(), self.bots): # wait for all the bots to start up time.sleep(CHECK_RATE) # start processing sockets with select self.should_take_measurements = take_measurements threading.Thread( name="loop %d" % hash(frozenset(map(lambda bot: bot.boundjid.full, self.bots))), target=lambda: self.select_loop() ).start() for index in range(len(self.bots)): #register message handlers on each bot self.bots[index].register_hexchat_handlers()
import asyncio import datetime import os, sys from bot import bot loop = asyncio.get_event_loop() bot = bot(loop=loop, max_messages=10000) if __name__ == "__main__": try: task = loop.create_task(bot.run()) bot.own_task = task loop.run_until_complete(task) loop.run_forever() except (KeyboardInterrupt, RuntimeError): print('\nKeyboardInterrupt - Shutting down...') bot.die() finally: print('--Closing Loop--') loop.close()
from mail import mail from wea import weather from bot import bot from wiki import wiki # Infinite Loop count = 0 while 1: tts(mail()) tts(weather('jabalpur')) tts(news()) while 1: string = str(input("Ask -> ")) if "weather report" in string: location = str(input("Enter LOC -> ")) tts(weather(location)) elif "news" in string: tts(news()) elif "mail" in string: tts(mail()) elif "song" in string: tts("Which song you wanna listen") song = str(input("Song -> ")) music(song) elif "neola" in string: string = string.replace("neola search ", "") tts(bot(string)) elif "wiki" in string: string = string.replace("wiki ", "") tts(wiki(string))
Descrição: Esse trabalho consiste na implementação de um chatbot simples, que responde de acordo com a proximidade do vetor tf-idf gerado pelo input do usuário com um dos vetores disponíveis no corpus. O corpus é constituido arquivo "Computer.txt", que contem o conteúdo disponével na página da wikipédia "https://en.wikipedia.org/wiki/Computer". As stopwords foram geradas utilizando o contúdo composto pelo livro "Frankenstein; Or, The Modern Prometheus", disponível em: "https://www.gutenberg.org/files/84/84-0.txt"; e pelo livro "The Adventures of Tom Sawyer", disponível em: "https://www.gutenberg.org/files/74/74-0.txt". Para testar basta executar este arquivo python e digitar algo, com relação a computadores, em inglês no terminal, o retorno será um documento do corpus, o mais similar, com relação ao input, encontrado pelos algoritmos. Algumas interações possíveis são: * when were computers invented? * what is computer i/o and networking? * tell about bugs * tell about early cpus * are bugs computer fault? * can computer do more than one thing at a time? * are computers calculating machines? ''' if __name__ == "__main__": bot()
class superbot(bot): def __init__(self, name, age, energy, shield_level, super_power_level=1): super().__init__(name, age, energy, shield_level) self.super_power_level = super_power_level def get_super_power(self): self.super_power_level = int( input("What is Super Bot a super power level? 1 to 5 \n")) if self.super_power_level >= 1 and self.super_power_level <= 5: print("Super Bot is charged") else: print("Invalid input") def display_super_power_level(self): print("\nSuper Power Energy level:") print( str("█" * int(self.super_power_level) + str("[]" * (5 - int((self.super_power_level)))))) def display_superbot_summary(self): return super().__str__() filip = superbot("Filip", 29, 90, 60) darren = bot("Darren", 30, 100, 30) noob = bot("noob", 15, 20, 50) filip.get_super_power() filip.display_super_power_level()
from bot import bot HOST = "" PORT = 6667 NICK = "pybot" CHANNELS = [] CHATLEVEL = 1 pybot = bot(HOST, PORT, NICK, CHANNELS, CHATLEVEL) pybot.learn("aiml sets/Professor/*") pybot.set_predicates("predicates.txt") pybot.connect() pybot.run()
def __init__(self, jid_passwords, whitelist, num_logins, sequential_bootup): """ Initialize a hexchat XMPP bot. Also connect to the XMPP server. 'jid' is the login username@chatserver 'password' is the password to login with """ #whitelist of trusted ip addresses client sockets can connect to #if None, can connect to anything self.whitelist=whitelist # <local_address> => <listening_socket> dictionary, # where 'local_address' is an IP:PORT string with the locallistening address, # and 'listening_socket' is the socket that listens and accepts connections on that address. self.server_sockets={} # <connection_id> => <xmpp_socket> dictionary, # where 'connection_id' is a tuple of the form: # (bound ip:port on client, xmpp username of server, ip:port server should forward data to) # and 'xmpp_socket' is a sleekxmpp socket that speaks to the XMPP bot on the other side. self.client_sockets={} #pending connections self.pending_connections={} #disconnects that go out when a resource is unavailable #maps key => set of recipient aliases to use for sending disconnects self.pending_disconnects={} #peer's resources self.peer_resources={} #for multiple logins self.connection_requests={} #number of times to login to each account self.num_logins=num_logins #locks self.client_sockets_lock=threading.Lock() self.pending_connections_lock=threading.Lock() self.peer_resources_lock=threading.Lock() self.connection_requests_lock=threading.Lock() self.pending_disconnects_lock=threading.Lock() #initialize the other sleekxmpp clients. self.bots=[] for login_num in range(self.num_logins): for jid_password in jid_passwords: self.bots.append(bot(self, jid_password)) if sequential_bootup: self.bots[-1].boot() else: threading.Thread(name="booting %d %d" % (hash(jid_password), login_num), target=lambda: self.bots[-1].boot()).start() while False in map(lambda bot: bot.session_started_event.is_set(), self.bots): time.sleep(CHECK_TIME) for index in range(len(self.bots)): self.bots[index].register_hexchat_handlers()
import bot from secrets import * """Notre super bot pendu""" if __name__ == "__main__": bot.bot(TOKEN)
if __name__ == '__main__': # Starts timer start = time() # Load settings settings = json_to_dict("/resources/settings.json") # Selects a verse from the bible verse, verse_index = select_quote() # Retrieves an image. pic_num = get_img(settings) # Processes bible-verse onto image. put_quote_on_wallpaper(sys.path[0] + '/resources/photo_of_the_day.jpg', verse, settings) # Creates tweet-header tweet, header_index = create_header(settings) # Uploads image and tweet-header to twitter success = bot(tweet, settings) # Stops timer end = time() time_spent = float("{0:.3f}".format(end - start)) # Writes debug-info to log-file logger.log(success, verse_index, header_index, pic_num, time_spent, None) os.remove(sys.path[0] + '/resources/photo_of_the_day.jpg')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 10 17:07:23 2018 @author: Alice & Paul """ from bot import bot if __name__ == '__main__': print("Here we go !") mybot = bot() print("I am " + mybot.name)
update_id = None RESULT_KEY: Final = "result" MESSAGE_KEY: Final = "message" CONFIG_FILE = "token.cfg" def make_reply(message): if message is not None: reply = "Okay" return reply while True: print("...") b = bot(CONFIG_FILE) updates = b.get_updates(offset=update_id) updates = updates[RESULT_KEY] if updates: for item in updates: update_id = item["update_id"] try: # fetching message content form Json message = item[MESSAGE_KEY]["text"] except ValueError(): message = None # gets the id of the person who sent the message # to the bot from_ = item[MESSAGE_KEY]["from"]["id"] reply = make_reply(message)
def test_bot(self): """test the bot message parser""" test_params = [ { KEY_TYPE: "ABOUT", KEY_INPUT: "!! about", KEY_EXPECTED: ("Hi, I am BobbyBot. I am a pretty fun guy. " +"If there is something you need from " +"me let me know. To find out what I am capable of type !! help") }, { KEY_TYPE: "HELP", KEY_INPUT: "!! help", KEY_EXPECTED: ("!! about - learn about me<br>!! help - shows " +"this screen<br>!! funtranslate " +"{message} - translate message to {language}<br>!! " +"flip - flip a coin<br>!! bitcoin - I will" +" tell you bitcoins price") }, { KEY_TYPE: "FUNTRANSLATE", KEY_INPUT: "!! funtranslate Testing this is fun.", KEY_EXPECTED: "esting-Tay is-thay is-way un-fay." }, { KEY_TYPE: "FUNTRANSLATE", KEY_INPUT: "!! funtranslate Super Duper Fun!", KEY_EXPECTED: "uper-Say uper-Day un-Fay!" }, { KEY_TYPE: "BITCOIN", KEY_INPUT: "!! bitcoin", KEY_EXPECTED: "1 bitcoin is currently worth money" }, { KEY_TYPE: "FLIP", KEY_INPUT: "!! flip", KEY_EXPECTED: "TEST" }, { KEY_TYPE: "FLIP", KEY_INPUT: "!! flip", KEY_EXPECTED: "TEST" }, { KEY_TYPE: "FLIP", KEY_INPUT: "!! flip", KEY_EXPECTED: "TEST" }, { KEY_TYPE: "FAIL", KEY_INPUT: "!! test", KEY_EXPECTED: "I don't know how to do that" }, { KEY_TYPE: "FAIL", KEY_INPUT: "!! !! bitcoin", KEY_EXPECTED: "I don't know how to do that" }, { KEY_TYPE: "FAIL", KEY_INPUT: "!! apple", KEY_EXPECTED: "I don't know how to do that" }, ] for test_case in test_params: response = bot(test_case[KEY_INPUT]) if test_case[KEY_TYPE] == 'FUNTRANSLATE' and response[:5] == 'Sorry': test_case[KEY_EXPECTED] = 'Sorry the limit for translations has been reached' elif test_case[KEY_TYPE] == 'BITCOIN' and "1 bitcoin is currently worth " in response: test_case[KEY_EXPECTED] = response elif test_case[KEY_TYPE] == 'FLIP' and ("HEADS" in response or "TAILS" in response): test_case[KEY_EXPECTED] = response self.assertEqual(response,test_case[KEY_EXPECTED])
def __init__(self, board_dimension, perform_experiments, tourney_rounds, human_playing): # Set global parameters self.board_dimension = board_dimension self.perform_experiments = perform_experiments self.tourney_rounds = tourney_rounds # Create our bots self.bot1 = bot('rnd', 'random', self.board_dimension) self.bot2 = bot('ab3R', 'alphabeta', self.board_dimension, search_depth=3, use_dijkstra=False, use_tt=False, id_time_limit=0) self.bot3 = bot('ab3D', 'alphabeta', self.board_dimension, search_depth=3, use_dijkstra=True, use_tt=False, id_time_limit=0) self.bot4 = bot('ab4D', 'alphabeta', self.board_dimension, search_depth=4, use_dijkstra=True, use_tt=False, id_time_limit=0) self.bot6 = bot('ab4D_TT', 'alphabeta', self.board_dimension, search_depth=4, use_dijkstra=True, use_tt=True, id_time_limit=0) self.bot7 = bot('ab_TT_ID1', 'alphabeta', self.board_dimension, search_depth=4, use_dijkstra=True, use_tt=True, id_time_limit=1) self.bot8 = bot('ab_TT_ID5', 'alphabeta', self.board_dimension, search_depth=4, use_dijkstra=True, use_tt=True, id_time_limit=5) self.bot9 = bot('ab_TT_ID10', 'alphabeta', self.board_dimension, search_depth=4, use_dijkstra=True, use_tt=True, id_time_limit=10) self.bot10 = bot('mcts500', 'mcts', self.board_dimension, iterations=500) self.bot11 = bot('mcts1k', 'mcts', self.board_dimension, iterations=1000) self.bot12 = bot('mcts5k', 'mcts', self.board_dimension, iterations=5000) self.bot13 = bot('mcts10k', 'mcts', self.board_dimension, iterations=10000) self.bot14 = bot('mctsinf_T1', 'mcts', self.board_dimension, iterations=1000000, mcts_time_limit=1) self.bot15 = bot('mctsinf_T5', 'mcts', self.board_dimension, iterations=1000000, mcts_time_limit=5) self.bot16 = bot('mctsinf_T10', 'mcts', self.board_dimension, iterations=1000000, mcts_time_limit=10) self.bot17 = bot('mctsinf_T1_C0.1', 'mcts', self.board_dimension, iterations=1000000, c_param=0.1, mcts_time_limit=1) self.bot18 = bot('mctsinf_T1_C0.5', 'mcts', self.board_dimension, iterations=1000000, c_param=0.5, mcts_time_limit=1) self.bot19 = bot('mctsinf_T1_C1.0', 'mcts', self.board_dimension, iterations=1000000, c_param=1, mcts_time_limit=1) self.bot20 = bot('mctsinf_T1_C1.5', 'mcts', self.board_dimension, iterations=1000000, c_param=1.5, mcts_time_limit=1) self.bot21 = bot('ab4D_TT_ID10', 'alphabeta', self.board_dimension, search_depth=4, use_dijkstra=True, use_tt=True, id_time_limit=10) self.bot22 = bot('mctsinf_T10_C0.5', 'mcts', self.board_dimension, iterations=1000000, c_param=0.5, mcts_time_limit=10) # Experiments self.ex1 = [self.bot2, self.bot3, self.bot4] self.ex2 = [self.bot4, self.bot6] self.ex3 = [self.bot7, self.bot8, self.bot9] self.ex4 = [self.bot10, self.bot11, self.bot12, self.bot13] self.ex5 = [self.bot14, self.bot15, self.bot16] self.ex6 = [self.bot17, self.bot18, self.bot19, self.bot20] self.ex7 = [self.bot21, self.bot22] # Create a gameboard self.gameboard = Gameboard(board_dimension) self.board = self.gameboard.board # Allow the human to play against the given bot if human_playing: res = self.Play_human_match(self.bot1, self.board) # Choose to perform experiments if self.perform_experiments: self.Perform_experiments(self.board, self.ex1) # Change the experiment here! print('End of experiments, shutting down.') exit(1) else: # Or just a few matches between two bots for _ in range(20): res = self.Play_single_bot_match(self.bot1, self.bot2, self.board) print("Player " + str(res) + " won")
#Section 1: Variable network = 'irc.nullstorm.r00t.la' port = 6667 channels = ["#aubcom", "#nullstorm", "#aubcom-dnd"] channel = "#aubcom" # primary channel for !j and !p nick = "dicey" chars = {} hp = {} CharPickleFile = "chars.pickle" HPPickleFile = "hp.pickle" # Init the bot module. irc = bot.bot(master="dushkin", channels=channels, nick=nick) #Section 2: Functions def TextEval(txt): # Evaluates text as math expression return float(eval(txt,{"__builtins__":None},safe_dict)) def Modifier(a): return math.floor((a-10)/2) def findKey(dic, val): for a in dic.items(): if v == val: return k
def main(usernameInput, passwordInput, width, height, hookName, token): # user inputs with open('save.txt', 'w') as f: f.write(usernameInput + ',' + passwordInput + ',' + width + ',' + height + ',' + hookName + ',' + token) # declaring the driver options = webdriver.ChromeOptions() options.binary_location = "C:/Program Files/Google/Chrome/Application/chrome.exe" chrome_driver_binary = "chromedriver.exe" driver = webdriver.Chrome(chrome_driver_binary, options=options) # driver = webdriver.Chrome() driver.set_window_position(0, 0) driver.set_window_size(width, height) # opening the website using get() driver.get('https://login.gitam.edu/Login.aspx') # setting user inputs to the portal # username username = driver.find_element_by_id('txtusername') username.send_keys(usernameInput) #password password = driver.find_element_by_id('password') password.send_keys(passwordInput) # clicking login button login = driver.find_element_by_id('Submit') login.click() # wait time for the site to load driver.implicitly_wait(30) myElem = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="form1"]/div[3]/section[2]/div/div/div[1]/h5'))) # clicking and opening glearn sitye glearn = driver.find_element_by_xpath('//*[@id="form1"]/div[4]/ul/li[1]') glearn.click() driver.execute_script('window.scrollTo(0, document.body.scrollHeight)') meetings = driver.find_elements_by_xpath('//*[@id="ContentPlaceHolder1_GridViewonline"]/tbody/tr') n = len(meetings) print(n, type(n)) meet = [] for i in range(1, n+1): details = [driver.find_element_by_xpath('//*[@id="ContentPlaceHolder1_GridViewonline"]/tbody/tr[' + str(i) + ']/td/a/div/h4').text, driver.find_element_by_xpath('//*[@id="ContentPlaceHolder1_GridViewonline"]/tbody/tr[' + str(i) + ']/td/a/div/h6').text, driver.find_element_by_xpath('//*[@id="ContentPlaceHolder1_GridViewonline"]/tbody/tr[' + str(i) + ']/td/a').get_attribute('href')] meet.append(details) # print(meet) with open("meet.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(meet) bot.bot(hookName, usernameInput) tbot.tbot(token) #looping all the available tabs def closeTab(): handles = driver.window_handles for handle in handles: #switching to the tab(handle) // here handle = (0, 1, 2, 3,....) driver.switch_to.window(handle) #printing the tab title print(driver.title) #closing the parent tab by checking the name if driver.title == "G-Learn": return else: driver.close() #clicking the Attendance button def Attendance(): closeTab() repeat = driver.find_element_by_link_text('Attendance') repeat.click() driver.implicitly_wait(5) #clicking the Home button def Home(): closeTab() repeatHome = driver.find_element_by_link_text('Home') repeatHome.click() driver.implicitly_wait(5) try: # looping through the pages in a 300s time interval // here 1 = 1s so, 300 = 300s = 5m while 1==1: # sleeping for 300s print('Sleeping for 300s') time.sleep(300) # navigating to the attendance page print('Clicking Attendance Page') Attendance() # sleeping for 300s print('Sleeping for 300s') time.sleep(300) # navigating to the home page print('Clicking Home Page') Home() except KeyboardInterrupt: # click ctr + c to interrupt and exit the program print("Thanks for using! Program is Exiting\nPress ctrl+c to exit") #quitting the browser after the interrupt driver.quit() exit()
from bot import bot from functions import run_bots bots = [] b = bot('irc.example.com', 6697, 'Nick', 'ident', 'realname', 'master', '#channel') bots.append(b) run_bots(bots)
def root(): return bot(request)
def neural_network(): from bot import bot return bot(request.args.get('msg'))
import os from flask import Flask, request import requests from bot import bot TOKEN = '664435594:AAHUcl61psQuC5LvPqq7L-JZvMCmOX62SGU' TOKEN2 = '405823545:AAHT8vByxjot138gjLW4LYT1qIWvALIxFMM' url = 'https://distaboo.pythonanywhere.com/' app = Flask(__name__) bot1 = bot(TOKEN, 406407068, app, url) bot2 = bot(TOKEN2, 406407068, app, url)
from data import checker checker.check() self.backk() elif pk == '2' or pk == '02': from data import checker checker.che() self.backk() elif pk == '3' or pk == '03': from data import checker checker.index() self.backk() else: exit('%s[!]%s Invalid Options.' % (R, N)) elif self.asw == '11': from data import bot bot.bot() self.backk() elif self.asw == '12': from data import yahoo_clone yahoo_clone.clon() self.backk() elif self.asw == '13': from data import app_check app_check.apps() self.backk() elif self.asw == '14': from data import listen listen.listen() elif self.asw == '15': print '[%s#%s] Updating Asu Toolkit ...' % (G, N) os.system('git pull')