def job_sending(bot: MyBot, chat_id: list, message: str, button: list, image_name: str): mess = message butt = button.copy() chat = chat_id.copy() url = image_name video_extension = ['avi', 'mp4', 'mkv', '3gp'] if url.split(".")[-1].lower() in video_extension: bot.send_video_with_button_caption(chat, mess, url, butt) else: bot.send_image_with_button_caption(chat, mess, url, butt)
def facebook_handler(event, context): env = Environment(api='facebook') for entry in event['entry']: for message in entry['messaging']: receiver_id = message['sender']['id'] if message.get('message', {}).get('text'): # text message in facebook msg = IncomingMessage( type=message_types.TEXT, payload=TextPayload(message['message']['text']), ) elif message.get('message', {}).get('attachments', []): # message w/ media attachment = message['message']['attachments'][0] msg = IncomingMessage( type='media', # your favorite type name payload=MediaPayload( type=attachment['type'], url=attachment['payload']['url'] ) ) else: msg = IncomingMessage( type=message_types.UNKNOWN, payload=None ) # WARNING: not good, use lambda's invokeFunction # to reply async and return response immediately MyBot(env, cache).reply(msg, receiver_id)
def main(is_master, map_name, races, portconfig, replay_path, log_path): portconfig = sc2.portconfig.Portconfig.from_json(portconfig) i = 0 if is_master else 1 player_config = [Bot(Race[r], None) for r in races] player_config[i].ai = MyBot() if log_path is not None: logger = logging.getLogger("sc2") logger.setLevel(logging.DEBUG) fh = logging.FileHandler(log_path) fh.setLevel(logging.DEBUG) logger.addHandler(fh) if is_master: g = sc2.main._host_game(sc2.maps.get(map_name), player_config, realtime=False, save_replay_as=replay_path, portconfig=portconfig) else: g = sc2.main._join_game(player_config, realtime=False, save_replay_as=replay_path, portconfig=portconfig) result = asyncio.get_event_loop().run_until_complete(g) print(result)
def __init__(self, sim_params, world_params, our_duckie_params, other_duckie_params): self.dt = sim_params["dt"] self.time = 0 self.road_width = world_params["road_width"] # Creating our duckie self.my_bot = MyBot(our_duckie_params, self.dt) # Creating other duckie if other_duckie_params["type"] == "constant_speed_duckie": self.other_bot = ConstantSpeedBot(other_duckie_params, self.dt) elif other_duckie_params["type"] == "unstable_speed_duckie": self.other_bot = UnstableSpeedBot(other_duckie_params, self.dt) else: rospy.logerr("[sim_node][world] Unknown other duckie type. Look in pathplan_uncertainty/config/sim.yaml and make sure it is fine!") self.my_bot_safety_status = self.check_safety(self.my_bot, self.other_bot) self.my_bot_ground_type = self.check_ground(self.my_bot.pos(), self.my_bot.radius)
def shell_handler(text): msg = IncomingMessage( type=message_types.TEXT, payload=TextPayload(text), ) env = Environment(api='stdout') MyBot(env, cache).reply(msg, None)
def __init__(self, manager=None, show_logs=False): self.manager = manager self.bots = [ MyBot(self.manager.dt), SlowBot(self.manager.dt) ] # Always keep MyBot as first bot otherwise my sh*tty code will break logging.getLogger().setLevel(logging.CRITICAL) if show_logs: logging.getLogger().setLevel(level=logging.INFO)
def slack_handler(event, context): env = Environment(api='slack_webhook') msg = IncomingMessage( type=message_types.TEXT, payload=TextPayload(event['text']), ) receiver_id = event['user_name'] MyBot(env, cache).reply(msg, receiver_id)
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game(maps.get("Abyssal Reef LE"), [Bot(race, MyBot()), Computer(Race.Random, Difficulty.Medium)], realtime=True)
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game(maps.get("Abyssal Reef LE"), [ Bot(Race.Zerg, Dummy()), Bot(race, MyBot()) ], realtime=True, game_time_limit=(60*10), save_replay_as="test.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game(maps.get("Abyssal Reef LE"), [ Bot(race, MyBot()), Computer(Race.Random, Difficulty.Medium) ], realtime=True, step_time_limit=2.0, game_time_limit=(60*20), save_replay_as="test.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] enemy_race = Race.Zerg if randrange(0,2) == 0 else Race.Protoss run_game(maps.get("Abyssal Reef LE"), [ Bot(race, MyBot()), Computer(enemy_race, Difficulty.Hard) ], realtime=False, step_time_limit=2.0, game_time_limit=(60*20), save_replay_as="test.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] bot = Bot(race, MyBot()) # Ladder game started by LadderManager print("Starting ladder game...") result, opponentid = run_ladder_game(bot) print(result, " against opponent ", opponentid)
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game(maps.get("Abyssal Reef LE"), [ Bot(race, MyBot(use_model=False)), Computer(Race.Zerg, Difficulty.Medium) ], realtime=False, game_time_limit=(60 * 45), save_replay_as="test.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] milliseconds = int(round(time.time() * 1000)) assure_path_exists("results/") replay_file = "replays/" + str(milliseconds) + ".SC2Replay" run_game(maps.get("Abyssal Reef LE"), [ Bot(race, MyBot()), Computer(Race.Random, Difficulty.Medium) ], realtime=False, game_time_limit=(60*20), save_replay_as=replay_file)
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game(maps.get("(2) Lost and Found LE"), [ Bot(race, MyBot()), Computer(Race.Terran, Difficulty.VeryHard), ], realtime=False, step_time_limit=2.0, game_time_limit=(60 * 20), save_replay_as="test.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game( pick_map(), [Bot(race, MyBot()), Computer(Race.Random, Difficulty.VeryHard)], realtime=False, step_time_limit= 0.5, # We use locally much stricter limit than in the competition game_time_limit=(60 * 60), # Challenge has 60min gametime limit save_replay_as="latest.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] lista_kartoista = ["(2)DreamcatcherLE", "(2)RedshiftLE", "AcolyteLE", "AbyssalReefLE"] random_kartta = random.choice(lista_kartoista) run_game(maps.get(random_kartta), [ #Human(Race.Terran), Bot(race, MyBot()), Computer(Race.Random, Difficulty.VeryHard) #Bot(race, WorkerRushBot()) ], realtime=False, step_time_limit=2.0, game_time_limit=(60*20), save_replay_as="test.SC2Replay")
class World(object): def __init__(self, sim_params, world_params, our_duckie_params, other_duckie_params): self.dt = sim_params["dt"] self.time = 0 self.road_width = world_params["road_width"] # Creating our duckie self.my_bot = MyBot(our_duckie_params, self.dt) # Creating other duckie if other_duckie_params["type"] == "constant_speed_duckie": self.other_bot = ConstantSpeedBot(other_duckie_params, self.dt) elif other_duckie_params["type"] == "unstable_speed_duckie": self.other_bot = UnstableSpeedBot(other_duckie_params, self.dt) else: rospy.logerr("[sim_node][world] Unknown other duckie type. Look in pathplan_uncertainty/config/sim.yaml and make sure it is fine!") self.my_bot_safety_status = self.check_safety(self.my_bot, self.other_bot) self.my_bot_ground_type = self.check_ground(self.my_bot.pos(), self.my_bot.radius) def step(self): for bot in [self.my_bot, self.other_bot]: # rospy.loginfo("[sim_node][world] Step at time: " + str(self.time) + " with "+ bot.type + ": " + str(bot.pos())) bot.sample_plan() self.time += self.dt self.my_bot_ground_type = self.check_ground(self.my_bot.pos(), self.my_bot.radius) self.my_bot_safety_status = self.check_safety(self.my_bot, self.other_bot) def get_state(self): return self.time, self.my_bot.pos(), self.my_bot.vel(), self.my_bot_safety_status, self.my_bot_ground_type, self.other_bot.pos(), self.other_bot.vel() def update_our_duckie_plan(self, plan): self.my_bot.update_plan(plan) def check_safety(self, my_bot, other_bot): x1, y1, _ = my_bot.pos() x2, y2, _ = other_bot.pos() # Checking if collision (assuming same circular shape for both bots) if (x1-x2)**2 + (y1-y2)**2 < (my_bot.radius + other_bot.radius)**2: rospy.loginfo("COLLISION!!!!") return SafetyStatus.COLLISION return SafetyStatus.FINE def check_ground(self, pose, radius): # Returns the type of ground for a duckie pose x = pose[0] if abs(x) <= 0.25*self.road_width - radius: return Ground.RIGHT_LANE elif x < -0.25*self.road_width + radius and x >= -0.75*self.road_width + radius: return Ground.WRONG_LANE elif (x > -0.75*self.road_width - radius and x < -0.75*self.road_width + radius) or (x > 0.25*self.road_width - radius and x < 0.25*self.road_width + radius): return Ground.PARTIALLY_OUT_OF_ROAD else: return Ground.LOST
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] opponents = [Computer(Race.Random, Difficulty.Hard)] map_pool = ["(2)dreamcatcherle", "(2)RedshiftLE", "(2)LostandFoundLE"] run_game(maps.get(random.choice(map_pool)), [Bot(race, MyBot()), random.choice(opponents)], realtime=False, step_time_limit=2.0, game_time_limit=(60 * 20), save_replay_as="test.SC2Replay")
def main(): with open("botinfo.json") as f: info = json.load(f) race = Race[info["race"]] run_game( maps.get("(2)DreamCatcherLE"), [ Bot(race, MyBot()), # Human(Race.Terran) # Bot(Race.Terran, ProxyRaxBot()) Computer(Race.Terran, Difficulty.VeryHard) ], realtime=False, step_time_limit=2.0, game_time_limit=(60 * 20), save_replay_as="./replays/{bot1}_vs_{bot2}_{map}_{time}.SC2Replay". format(bot1="MyBot", bot2="TerranElite", map="DreamcatcherLE".replace(" ", ""), time=time.strftime("%H_%M_%j")))
def main(): from bot import MyBot bot = MyBot(read_keys("..\\.data\\key.txt"), "!") bot.wake()
# Create a trace activity that contains the error object 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") # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity) ADAPTER.on_turn_error = MethodType(on_error, ADAPTER) # Create the main dialog BOT = MyBot() # Listen for incoming requests on /api/messages. @APP.route("/api/messages", methods=["POST"]) def messages(): # Main bot message handler. 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 "")
import logging from bot import MyBot import settings from requests.exceptions import ReadTimeout if __name__ == "__main__": # On set le logging logging.basicConfig(format='%(asctime)-15s [%(levelname)s] (%(name)s) %(message)s', level=logging.INFO) # On créé l'objet bot avec la config passée dans le fichier settings (depuis l'import settings) bot = MyBot(settings.CHAN, settings.NICKNAME, settings.SERVER, settings.PORT) while True: try: logging.info('Demarrage de la surveillance de masse') bot.start() except ReadTimeout: logging.error('Read timeout, restarting bot.')
ADAPTER.on_turn_error = on_error # Create MemoryStorage and state MEMORY = MemoryStorage() USER_STATE = UserState(MEMORY) CONVERSATION_STATE = ConversationState(MEMORY) # Create Queue to menage access to File feedback QUEUE = asyncio.Queue(4) #initial values QUEUE.put_nowait(0.125) QUEUE.put_nowait(0.125 * 2) QUEUE.put_nowait(0.125 * 3) QUEUE.put_nowait(0.125 * 4) # Create the Bot BOT = MyBot(USER_STATE, CONVERSATION_STATE, QUEUE) # Listen for incoming requests on /api/messages async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body) auth_header = req.headers[ "Authorization"] if "Authorization" in req.headers else "" try:
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", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity) ADAPTER.on_turn_error = on_error # Create the Bot BOT = MyBot(CONFIG) # Create the bot # BOT = EchoBot(CONFIG) # Listen for incoming requests on /api/messages async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body) auth_header = req.headers[
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", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity) ADAPTER.on_turn_error = on_error # Create the Bot BOT = MyBot(CONVERSATION_STATE) # Listen for incoming requests on /api/messages async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body) auth_header = req.headers[ "Authorization"] if "Authorization" in req.headers else "" try:
value=f"{error}", value_type="https://www.botframework.com/schemas/error", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. ADAPTER.on_turn_error = on_error # Create the Bot RECOGNIZER = MusicRecognizer(CONFIG) RECOMMENDATION_DIALOG = RecommendationDialog(RECOGNIZER) DIALOG = MainDialog(RECOGNIZER, RECOMMENDATION_DIALOG) BOT = MyBot(RECOGNIZER, CONVERSATION_STATE, USER_STATE, DIALOG) # Listen for incoming requests on /api/messages async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body) auth_header = req.headers[ "Authorization"] if "Authorization" in req.headers else "" response = await ADAPTER.process_activity(activity, auth_header,
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", ) # Send a trace activity, which will be displayed in Bot Framework Emulator await context.send_activity(trace_activity) ADAPTER.on_turn_error = on_error # Create the Bot BOT = MyBot(CONVERSATION_STATE, USER_STATE) # Listen for incoming requests on /api/messages async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body) auth_header = req.headers["Authorization"] if "Authorization" in req.headers else "" response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn) if response:
from bot import MyBot import os from os.path import join, dirname from dotenv import load_dotenv from cogs.utils.helpcommand import PaginatedHelpCommand dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) bot = MyBot('/', help_command=PaginatedHelpCommand()) extensions = [ 'cogs.manager', 'cogs.webhook', 'cogs.admin', 'cogs.meta', 'cogs.subscription', ] for extension in extensions: bot.load_extension(extension) bot.run(os.environ.get('TOKEN'))
from bot import MyBot from extra import bot_id, chat_id from utils import download_image, download_video, delete_video_photo, job_sending import threading import telegram import telegram.ext import time import os from apscheduler.schedulers.blocking import BlockingScheduler print("starting...") token = os.getenv('my_token') bot = MyBot(bot_token=token) sch = BlockingScheduler() send_message = True has_message = False video_extension = ['avi', 'mp4', 'mkv', '3gp'] duration = 10 message = [] button_url = [] button_text = ['order', 'service'] current_command = '' temp_but = [] buttons = [] message_sending_index = 0 list_of_active_jobs = [] list_of_time = [] attatchents = [] job_ids = [] temp = [] #####################ui############################################### help_button = telegram.InlineKeyboardButton(
from config import Config from bot import MyBot from cogs import Greetings COGS_LIST = [Greetings] if __name__ == '__main__': bot = MyBot(command_prefix='.') for cog in COGS_LIST: bot.add_cog(cog(bot)) bot.run(Config.token)