def bot(session): return Bot(session=session)
from bot import Bot if __name__ == '__main__': bot = Bot() bot.run("Discord-Bot-Client-Token") # Discord bot token
def createBots(screen, settings, Bots): for i in range(settings.botMax): newBot = Bot(screen, settings) newBot.id = i + 1 newBot.x += newBot.id * .5 Bots.append(newBot)
import libneko from discord.ext import commands from bot import Bot __version__ = '0.0.1-p80' # install pilutils after new setuptools has been built os.system("pip install git+https://github.com/Supersebi3/pilutils") logging.basicConfig(level=logging.INFO) intents = discord.Intents.default() #intents.message_content = True bot = Bot(command_prefix="s#", intents=intents) @bot.command() async def test(ctx): await ctx.sendstr( "commands.test", sys.version, discord.__version__, libneko.__version__, __version__, ) @bot.listen() async def on_ready():
from config import config, tg_bot, yandex_api app = Flask(__name__) sslify = SSLify(app) app.config['DEBUG'] = config['DEBUG'] app.config['SQLALCHEMY_DATABASE_URI'] = config['SQLALCHEMY_DATABASE_URI'] app.config["SQLALCHEMY_POOL_RECYCLE"] = 299 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = config[ 'SQLALCHEMY_TRACK_MODIFICATIONS'] import database import telebot from bot import Bot from telebot import types bot = Bot(tg_bot['token']) from api import YandexAPI obj_yandex_api = YandexAPI(key=yandex_api['key'], url=yandex_api['url']) from math import cos, radians @app.route('/{}'.format(tg_bot['token']), methods=["POST"]) def webhook(): bot.process_new_updates() return "ok", 200 def preprocessing(message): user_id = message.from_user.id
import os, time import redis from rq import Connection, Worker, Queue from flask import Flask from bot import Bot bot = Bot("main_bot") r = bot.get_relays() app = Flask( __name__, template_folder="../client/templates", static_folder="../client/static", ) # set config app_settings = os.getenv("APP_SETTINGS") app.config.from_object(app_settings) redis_url = app.config["REDIS_URL"] #start the worker redis_connection = redis.from_url(redis_url) with Connection(redis_connection): q = Queue() q.empty() worker = Worker(app.config["QUEUES"]) worker.work()
def test_create(): ex = Executor("foo") bot = Bot(ex) assert bot.executor == ex
start = time() with open("config.EXAMPLE.yml", "r") as f: game_config = yaml.safe_load(f) newgame("testing", game_folder, game_config) stop = time() logger.debug(f"{LOG_LEVEL(1)}# Timing # game creation in {(stop-start)*1000:.1f} ms") # init bots start = time() logger.info(f"{LOG_LEVEL(0)}Creating Bots...") bots = [] for i in range(1, 4): # bot 1 with open(f"bot_config.EXAMPLE{i}.yml", "r") as f: bot_config = yaml.safe_load(f) bots.append(Bot(bot_config, game_folder)) stop = time() logger.debug(f"{LOG_LEVEL(1)}# Timing # Bots creation in {(stop - start) * 1000:.1f} ms") # play some turns for turn_nb in range(0, 10): logger.info(f"{LOG_LEVEL(0)}--- TURN {turn_nb} ---") # bots play logger.info(f"{LOG_LEVEL(1)}bots reads report from turn {turn_nb}, make choices and writing orders for turn {turn_nb+1}") start = time() for bot in bots: report = get_report(bot.name, game_folder, turn_nb) bot.play_turn(report) bot.write_order() stop = time() logger.debug(f"{LOG_LEVEL(1)}# Timing # Bots playing in {(stop - start) * 1000:.1f} ms")
from nlp_rivescript import Nlp from datetime import datetime, timedelta import os import MySQLdb import requests import urllib import time from decimal import Decimal from bjpay_service import BJPayService from bot import Bot lineNlp = Nlp() bjp = BJPayService() bot = Bot( '4NzXHLlCrtqIyNkIizW7Bte1pys9WNUb4Nl1Uv7c2pZNrPZB/D9e2HsbXsUzPyXrcfwzA163oT9a4HkcmkomJwCI6Xn0Rlv/2bmd3numlH2vkosW7TbXZAGFR84/jEn79jiq/hF20HQ5HN0E/x0PPn6Nfd2Y6SKCxBWg7Cr7O3c=' ) def update_saldo(msisdn, amount): print "==============================================================================================" payload = lineNlp.redisconn.get("bjpay/" + msisdn) current_balance = int(payload.split('|')[0]) va_no = payload.split('|')[1] phone = payload.split('|')[2] print "MSISDN : " + msisdn + ", Payload : " + payload print "Current balance : " + str(current_balance) added_balance = (current_balance + int(amount)) payload = str(added_balance) + "|" + va_no + "|" + phone lineNlp.redisconn.set("bjpay/%s" % (msisdn), payload) print "Add " + str(amount) + " to current balance = " + str(
from argparse import ArgumentParser from os.path import dirname, realpath from bot import Bot, Tasks, Responses from actions import actions from coroutines import coroutines parser = ArgumentParser(description="A meta bot for ~team") parser.add_argument("-c", "--config", dest="config", default="settings.json", help="Load config file") arguments = parser.parse_args() bot = Bot("127.0.0.1", 6667) responses = Responses(bot) tasks = Tasks(bot) # for coro in coroutines: # worker = coro["worker"] # interval = coro["interval"] # state = coro.get("state", None) # coro_state = state if state is not None else (bot,) # tasks.add_coroutine(worker, interval, coro_state) tasks.coroutines = coroutines for action in actions: if "type" in action and "pattern" in action and "callback" in action: responses.add_trigger(action["type"], action["pattern"], action["callback"])
def start_game(self): node = None print("Select the board configuration you want to play") try: board_created = False while (not board_created): try: numOfSquares = int(input("1. 6x6 \t2. 8x8 \t3.10x10 \n")) if (numOfSquares == 1): board = Board.Board(6) break elif (numOfSquares == 2): board = Board.Board(8) break elif (numOfSquares == 3): board = Board.Board(10) break except (KeyboardInterrupt, SystemExit) as e: sys.exit(0) except: print("Enter Input in the proper format") # Add 3 obstacles obstacles = board.set_obstacles(3) print(f"Obstacles added at {obstacles}") # Let player1 choose his Control action player1_selected = False player1_select = 0 while not player1_selected: try: player1_select = int( input( "Choose player 1 Control : \n1: Human \t2: BaseLine AI \t3: MCTS AI " "\t4: NN+MCTS AI")) if player1_select == 1 or player1_select == 2 or player1_select == 3 or player1_select == 4: player1_selected = True except (KeyboardInterrupt, SystemExit) as e: sys.exit(0) except: print("Enter Input in the proper format") # Let player2 choose his Control action player2_selected = False player2_select = 0 while not player2_selected: try: player2_select = int( input( "Choose player 2 Control: \n1: Human \t2: BaseLine AI \t3: MCTS AI " "\t4: NN+MCTS AI")) if player2_select == 1 or player2_select == 2 or player2_select == 3 or player2_select == 4: player2_selected = True except (KeyboardInterrupt, SystemExit) as e: sys.exit(0) except: print("Enter Input in the proper format") game_bot = Bot() player_1 = Player(True) player_2 = Player(False) nodes_processed = 0 num_passes = 0 while not board.check_game_status(): print(board) print(f"Move #: {board.total_moves}") prev_move = board.total_moves if board.total_moves % 2 == 0: if player1_select != 1: print("AI Turn\n") else: print("Player1, It's your turn to play\n") else: if player2_select != 1: print("AI Turn\n") else: print("Player2, It's your turn to play\n") # Player1 Turn pawn_selected = False if board.total_moves % 2 == 0: if player1_select == 1: player_1.player_human(board, board.p1_pawns) else: if player1_select == 2: node = player_1.player_BaseLine_AI(game_bot, board) elif player1_select == 3: node = player_1.player_MCTS_AI(game_bot, board) elif player1_select == 4: node = player_1.player_NN_MCTS_AI(game_bot, board) if node: board = node.state else: break else: if player2_select == 1: player_2.player_human(board, board.p2_pawns) else: if player2_select == 2: node = player_2.player_BaseLine_AI(game_bot, board) elif player2_select == 3: node = player_2.player_MCTS_AI(game_bot, board) elif player2_select == 4: node = player_2.player_NN_MCTS_AI(game_bot, board) if node: board = node.state else: break if board.total_moves == prev_move: num_passes += 1 else: num_passes = 0 if num_passes == 5: break print("Game Over\n") winner = board.declare_winner() if winner == 1: print("Congratulations! Player1. You Won!!") print(f"Score = {board.compute_score()}") elif winner == -1: print("Congratulations! Player2. You Won!!") print(f"Score = {board.compute_score() * -1}") else: print("It's a Tie") except Exception as e: print(f"Error Occurred: {e}")
from bot import Bot vk_bot = Bot()
def main(): Database.prepare_db(config["database_file"]) bot = Bot(**config) bot.start() bot.idle()
from dotenv import load_dotenv import utils from bot import Bot try: debug = True if sys.argv[1] == 'debug' else False except IndexError: debug = False log = utils.setup_log() dotenv_path = utils.find(os.path.dirname(os.path.abspath(__file__)), '.env_debug' if debug else '.env') load_dotenv(dotenv_path) token = os.getenv('DISCORD_TOKEN') bot = Bot(pfx='!', debug=True if debug else False) @bot.event async def on_disconnect(): log.warning('Removing last video files before disconnecting.') for guild in bot.guilds: path = bot.settings.get(guild.id).get('yt_file') if os.path.exists(path): os.remove(path) log.warning(f'Removed {path}') @bot.event async def on_ready(): guilds = await bot.fetch_guilds().flatten()
yield finally: # __exit__ for handler in log.handlers[:]: handler.close() log.removeHandler(handler) def check_token(configuration): token = configuration.get(ConfigNode.TOKEN) if token == ConfigNode.TOKEN.get_value(): logger.warning( "The config file is either newly generated or the token was left to its default value. \n" "Please enter your bot's token:") try: token = input() configuration.set(ConfigNode.TOKEN, token) except KeyboardInterrupt: logger.error("Interrupted token input") sys.exit() if __name__ == '__main__': with setup_logging(): config = ConfigFile("config") check_token(config) intents = discord.Intents.default() intents.message_content = True Bot(config, intents).start_bot()
#a dictionary of mood-quote pairings bot_quotes = \ { "calm" : [" That's what I thought. ", " Ok cool.", " nice ;)"], "mad" : [" No u ", " Blimey mate, don't have feelings of anger towards me because I'm a more dazzing fellow."], "ironic" : [" The reddit hivemind continues... ", " Have you ever heard the tragedy of Darth Plagueis the Wise?"], } #setup reddit reddit = praw.Reddit('bot1') subreddit = reddit.subreddit("pythonforengineers") #instantiate Bot my_bot = Bot("Sir Bottington The Third", bot_quotes) found_comment = False #loop through the top five posts in the subreddit's hot section for submission in subreddit.hot(limit=5): if not submission.archived: for comment in submission.comments: print(comment.body) if re.search(".*(IMO)+.*", comment.body, re.IGNORECASE): my_bot.change_mood("calm") found_comment = True elif re.search(".*((left)+(right)*)|((left)*(right)+)+.*", comment.body, re.IGNORECASE): my_bot.change_mood("ironic") found_comment = True elif re.search(".*((you)+((stupid)*(idiot)*(suck)*)+)+.*", comment.body, re.IGNORECASE): my_bot.change_mood("mad")
from misc.adapter import create_bot, connect_bot from bot import Bot if __name__ == "__main__": rf = Bot() bot = create_bot(rf, rf.config.get("cmd-prefix", ".")) rf.bot = bot connect_bot(bot)
def create_app(): app = Flask(__name__) ACCESS_TOKEN = 'ACCESTOKEN' VERIFY_TOKEN = 'TESTINGTOKEN' bot = Bot(ACCESS_TOKEN) def interrupt(): global yourThread yourThread.cancel() def doStuff(): global yourThread global studenttocheck with dataLock: # Do your stuff with commonDataStruct Here print(studenttocheck) for student in studenttocheck: print( str(datetime.now())[11:-7] + " Scan de " + student["prenom"]) result = checknewnote(student["numero"]) if result == 0: print("Pas de nouvelle note") elif result == -1: print("Erreur lors du check de " + student["prenom"]) else: for i in result: send_message( student["idmes"], "Nouvelle note en " + i + " : " + result[i]) print("Nouvelle note en " + i + " : " + result[i]) # Set the next thread to happen yourThread = threading.Timer(POOL_TIME, doStuff, ()) yourThread.start() def doStuffStart(): # Do initialisation stuff here global listname global listenumero global studenttocheck login() falselisteeleves() listname = listenom1a + listenom2a listenumero = listenumero1a + listenumero2a # Ouverture de la liste des personnes if is_non_zero_file(nomfichierabo) == 0: with open(nomfichierabo, 'wb') as file: pickler = pickle.Pickler(file) pickler.dump(studenttocheck) file.close() print("Nouveau fichier creer") else: # Ouverture des fichier contenant les personnes with open(nomfichierabo, 'rb') as file: depickler = pickle.Unpickler(file) studenttocheck = depickler.load() file.close() for i in range(len(listname)): listname[i] = listname[i].upper() global yourThread # Create your thread yourThread = threading.Timer(POOL_TIME, doStuff, ()) yourThread.start() @app.route("/", methods=['GET', 'POST']) def receive_message(): # print("Message recu") if request.method == 'GET': """Before allowing people to message your bot, Facebook has implemented a verify token that confirms all requests that your bot receives came from Facebook.""" token_sent = request.args.get("hub.verify_token") return verify_fb_token(token_sent) # if the request was not get, it must be POST and we can just proceed with sending a message back to user else: # get whatever message a user sent the bot output = request.get_json() for event in output['entry']: messaging = event['messaging'] for message in messaging: if message.get('message'): # Facebook Messenger ID for user so we know where to send response back to recipient_id = message['sender']['id'] print("Nouveau message de : " + bot.get_user_info(message['sender']['id']) + " :") if message['message'].get('text'): print(message['message'].get('text')) response_sent_text = get_message(message) send_message(recipient_id, response_sent_text) # if user sends us a GIF, photo,video, or any other non-text item if message['message'].get('attachments'): response_sent_nontext = "Merci" send_message(recipient_id, response_sent_nontext) return "Message Processed" def verify_fb_token(token_sent): # take token sent by facebook and verify it matches the verify token you sent # if they match, allow the request, else return an error if token_sent == VERIFY_TOKEN: return request.args.get("hub.challenge") return 'Invalid verification token' # chooses the message to send to the user def get_message(message): if not next((item for item in studenttocheck if item["idmes"] == message['sender']['id']), None): # If the person is not in the list # We look for who is the person: first_name = bot.get_user_info( message['sender']['id'])["first_name"] last_name = bot.get_user_info(message['sender']['id'])["last_name"] name = last_name + " " + first_name if name.upper() in listname: promethee_number = listenumero[listname.index(name.upper())] studenttocheck.append({ "numero": promethee_number, "idmes": message['sender']['id'], "nom": last_name, "prenom": first_name }) with open(nomfichierabo, 'wb') as file: pickler = pickle.Pickler(file) pickler.dump(studenttocheck) file.close() response = "Je t'ai ajouté à la liste mon petit " + first_name else: response = "Je ne sais pas qui t'es, j'ai demandé à baptiste de la faire manuellement" bot.send_text_message( '2621783057950447', "Aledfrr j'arrive pas a ajouter " + name + " " + message['sender']['id']) else: action, response = dialogquerry(message['message'].get('text')) if action == "Menu": sample_responses = [ "Send 'note' to get your grade (you must be in the database) or send 'Quit' to get removed from the database." ] elif action == "Note": notes = noteseleve( next((item for item in studenttocheck if item["idmes"] == message['sender']['id']), None)["numero"]) answer = "Notes de " + str( bot.get_user_info( message['sender']['id'])["first_name"]) + ":\n" for i in notes.keys(): answer = answer + i + " : " + str(notes[i]) + "\n" response = response + " :\n" + answer notes.clear() # despicable : # nomfichier = "notes/" + str(4379) # # if is_non_zero_file(nomfichier) == 0: # nouveaufichier = 1 # else: # # Ouverture des fichier contenant les notes # with open(nomfichier, 'rb') as fichier: # mon_depickler = pickle.Unpickler(fichier) # notesfichier = mon_depickler.load() # fichier.close() # # sample_responses = [str(notesfichier)] elif action == "QUIT": sample_responses = ["Je suis triste, à bientot"] # Remove the person from the list if exists if next((item for item in studenttocheck if item["idmes"] == message['sender']['id']), None) in studenttocheck: studenttocheck.remove( next((item for item in studenttocheck if item["idmes"] == message['sender']['id']), None)) with open(nomfichierabo, 'wb') as file: pickler = pickle.Pickler(file) pickler.dump(studenttocheck) file.close() else: bot.send_text_message( '2621783057950447', "Aledfrr j'arrive pas a supprimer " + bot.get_user_info( message['sender']['id'])["first_name"] + " " + message['sender']['id']) elif action == "Default Fallback Intent": if message['sender']['id'] == "3190229520988487": response = random.choice([ "Ferme la grosse merde", "Je te déteste Arthur", "Get cancer and die plz", "Puterelle", "Tu vois, ça, c’est la raison pour laquelle les gens parlent mal de toi quand t’es pas là", "Je trouve ça absolument génial, cette manière bien à toi que tu as de dire des trucs absolument évidents avec la sincère conviction que tu as découvert quelque chose", "C’est bon, tu as terminé ?", "Tu n’es vraiment pas assez beau pour pouvoir te permettre d’être aussi bête", "Est-ce que tu te rends compte que les gens ne font que te tolérer ?" ]) else: sample_responses = [ "Je suis un bot", "C'est moi qui envoie les messages", "Bonjour a toi" ] # print(bot.get_user_info(message['sender']['id'])) # return selected item to the user # return random.choice(sample_responses) return response # uses PyMessenger to send response to user def send_message(recipient_id, reply): # sends user the text message provided via input response parameter bot.send_text_message(recipient_id, reply) print("Envoi du message: " + reply) return "success" # Initiate doStuffStart() # When you kill Flask (SIGTERM), clear the trigger for the next thread atexit.register(interrupt) return app
async def test_interface(): ex = Executor("foo") bot = Bot(ex) with pytest.raises(NotImplementedError): await bot.turn(None)
def timed_run(): bot = Bot() bot.run()
if settings.stop_interval > settings.main_counter: if settings.main_counter % 4 // 2 == 1: bot_el.draw() else: bot_el.draw() if (settings.bots_spawn_counter % settings.bots_spawner_speed == 0 and settings.bots_spawned < settings.enemies_at_level ) or settings.bots_spawn_counter == 5: while True: bot_index = rnd(0, 3) if settings.bots_nums[bot_index] != 0: break settings.bots_nums[bot_index] -= 1 settings.bots.append(Bot(settings, bot_index)) settings.bots_spawner_speed -= 3 settings.bots_spawned += 1 for block in settings.armor: block.draw() hp = 0 for tank in settings.tanks: hp += tank.health if (hp) == 0 and settings.enemies_left != 0: settings.enemies_left = 0 settings.cur_level = 0 settings.stop_game = True
from bot import Bot robot = Bot() robot.run()
from modules import logging from modules import messages #======================================= # Variables #======================================= # Globals null = -1 NONE = messages.MessageType.NONE # Local socket variables. buffer = 4096 irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Local instance of Autumn. bot = Bot(irc, buffer) #======================================= # Classes #======================================= class Sentinel(object): def __init__(self, bot, path="/plugins"): self.bot = bot self.path = path async def refresh(self, time=1): while True: self.bot.load_plugins(self.path) await asyncio.sleep(time) @staticmethod
'Oh, please, stop it'), SimpleMatcher('any(Haha,hahaha,ahaha)', '😅', '☺️'), # story telling SimpleMatcher( 'If $something+ then $something_other+', 'Are you sure about such consequences?', 'Ok, but what if "{something_other}" won\'t happen? Is it a bad thing at all?' ), # Other SimpleMatcher('any(Yes,No)', '✅✅', 'Ok then', 'Cool!'), SimpleMatcher('any(Yes,No) ...', '✅✅', 'Ok then', 'Cool!'), SimpleMatcher('any(Hm,hmm)', 'What are you thinking about?', 'Hm...?'), SimpleMatcher('any(rly,really)', 'No doubt!', 'Yeees', 'Sure!'), # General response in case of misunderstanding SimpleMatcher('*', 'Could you rephrase it? I did not follow', '🤷🏿♂️', '👽'), ) if __name__ == '__main__': ds = get_dialogue_system() token = os.getenv('TG_TOKEN') print(token, flush=True) if token: bot = Bot(token=token, text_handler=ds.get_response) bot.run() else: run_console_dialogue(ds.get_response)
def main(): with open('token.txt', 'r') as f: token = f.read().strip() bot = Bot(token) bot.add_handlers() bot.start()
# --------------------------- Init Client ------------------------------------------- try: # request_client = RequestClient(api_key=key, secret_key=secret, url='https://testnet.binancefuture.com/') request_client = RequestClient(api_key=key, secret_key=secret, url='https://fapi.binance.com') # request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key, url='https://testnet.binancefuture.com/') except Exception as e: print("ERROR: Connecting to client") else: print("INFO: Connected to client") # coin = 'BTCUSDT' # minimalQtd = 0.001 # minimalProfit = 0.5 # leverage = 100 backtest = Bot(request_client, coin, float(minimalQtd), float(minimalProfit), float(leverage), float(minimalMove)) # try: # # close = numpy.random.random(100) # print(close) # moving_average = talib.RSI(close) # # print(moving_average) # except Exception as e: # print("EROOR") # This function provides utility functions to work with Strings # 1. reverse(s): returns the reverse of the input string
try: from .deathbot.bot import Bot except: from bot import Bot Bot(name="Deathbot").play()
if context.activity.channel_id == 'emulator': # se crea una actividad conteniendo info del error trace_activity = Activity( label="TurnError", name="on_turn_error Trace", timestamp=datetime.utcnow(), type=ActivityTypes.trace, value=f"{error}", value_type="https://www.botframework.com/schemas/error" ) # Se muestra la actividad en el Bot Framework Emulator await context.send_activity(trace_activity) ADAPTER.on_turn_error = on_error BOT = Bot() @App.route('/api/messages', methods=['POST']) def messages(): if "application/json" in request.headers["Content-Type"]: body = request.json else: return Response(status=415) activity = Activity().deserialize(body) auth_header = ( request.headers["Authorization"] if "Authorization" in request.headers else "" ) try:
def __init__(self, request=None, response=None): super(MainPage, self).__init__(request, response) logging.info("Instanciando bot") tree = yaml.load(open('tree.yaml')) logging.info("Tree: %r", tree) self.bot = Bot(send_message, UserEventsDao(), tree)
from plugins.imgur import Imgur from plugins.logger import Logger import threading from bot import Bot from config import Config Settings = Config('config.yaml') CubicNinja = Bot(Settings) CubicNinja.connect('ws://sim.smogon.com:8000/showdown/websocket') CubicNinja.login(Settings) for i in Settings.autojoin_rooms: CubicNinja.send('|/join ' + i) ChatLoop = threading.Thread(target=CubicNinja.chatLoop) ChatLoop.start()