def lambda_handler(event, context): time = datetime.now(timezone('US/Pacific')) callHour = time.hour callMin = time.minute timeRange = range( callMin - 4, callMin + 5) # Account for delays, which can apparently be in the minutes on AWS bot.main(0) if callHour % 2 == 0 and 0 in timeRange: bot.main(1) return {'statusCode': 200}
def test_validRetweets(self): # Given list of Mock tweets mock_t_list = [ mock_t("user", "I study English."), mock_t("user", "I study Japanese."), mock_t("user", "I study Korean."), ] # When we call api to return our list of tweets # Mock response bot.main(mock_t_list, mydb, mycursor, 0) # Then assert we get the "Tweets retweeted" status for each tweet return
def post(self): jid = self.request.get("from") body = self.request.get("body") req = {} req["from"] = {"full": jid, "node": jid.split("/")[0].split("@")[0], "domain": jid.split("/")[0].split("@")[1], "resource": jid.split("/")[1]} req["raw"] = body response = bot.main(req) xmpp.send_message(jid, response)
def run(self): loop = asyncio.get_event_loop() if sys.platform == 'win32': signal.signal(signal.SIGTERM, bot.sigterm_handler) else: for signame in ('SIGINT', 'SIGTERM'): loop.add_signal_handler(getattr(signal, signame), functools.partial(bot.sigterm_handler, signame)) loop.call_later(3, self.flush_err) loop.run_until_complete(bot.main(loop)) loop.close()
def GET(self): global grid global player_id # print "AI MOVES BITCHES!!!" win = 0 validity = web.input(valid=None) if int(validity.valid) == 1: #print "HELL YEAH" # print "Player id? is "+str(player_id) postion = bot.main(grid, player_id) x = postion[0] y = postion[1] # need this to determine winner old = copy.deepcopy(grid) grid = logic.move(x, y, player_id, grid) if player_id == 1: player_id = 2 else: player_id = 1 # determining if someone won or not? old1 = 0 old2 = 0 new1 = 0 new2 = 0 for i in range(5): for j in range(5): if old[i][j] / 10 == 1: old1 += 1 if old[i][j] / 10 == 2: old2 += 1 if grid[i][j] / 10 == 1: new1 += 1 if grid[i][j] / 10 == 2: new2 += 1 if old1 != 0 and new1 == 0: win = 2 elif old2 != 0 and new2 == 0: win = 1 if win != 0: games.update({'_id': gameid}, {'$set': {"win": win}}) return render.game(input=grid, player=player_id, winner=win, Mtype=matchType, p1=NameP1, p2=NameP2)
def main(): args = create_parser().parse_args() if args.bot: bot.main() else: config = Config().data data = Data(config.get('db')) monitor = Monitor( monitor=config.get('monitor'), proxies=config.get('proxies'), telegram=config.get('telegram'), ) data.add_keywords(initial=True) monitor.main( data, config.get('urls', []), )
if remaining: print('Backlinks left behind:', remaining) else: print('Backlinks clear.') def _request_delete(self, page): 'Request speedy deletion.' message = '{0.CYAN}{1.name} -> {0.RED}DELETE{0.RESET}' print(message.format(colorama.Fore, page)) self._confirm(page, '{{d|R3|G10}}') def _save(self, page, result, verbose=False, move=False): 'Request a page move.' if not move: return super()._save(page, result, verbose) if verbose is True: print('Moving...', end=' ') page.move(result, self.edit_summary) if verbose is True: print('Done.') elif verbose: print(verbose, end='') return True if __name__ == '__main__': main(PageMover, argc=3)
def tweet_job(): bot.main()
def __call__(self, edit_summary, minor=False): 'Check all pages onto which the airport infobox is transcluded.' super().__call__(edit_summary, minor) pages = self.site.pages[self.template].embeddedin() for page in gevent.pool.Pool(100).imap(self._parse, pages): pass self._show_stat() def _parse(self, page): 'Extract the airport codes from articles.' if page.namespace: # not in the article namespace, hence ignore it return next(self) for pattern in self.patterns: match = re.search(pattern, page.text()) if match: self._create_redirect(page, airport_code=match.group(1)) def _create_redirect(self, page, airport_code): 'Create a redirect page if the page title does not exist yet.' redirect_page = self.site.pages[airport_code] if redirect_page.exists: return next(self) else: self._save(redirect_page, self.repl.format_map(vars()), '#') if __name__ == '__main__': gevent.monkey.patch_all() main(AirportBot)
for city in cities.split(','): super().__call__(*globals()[city](), self.__doc__, minor) def nanchang(): template = '南昌地铁线路名' single_line = r'(\{\{%s\|\d+)\|block(\}\})' % template pattern = r'(?<=是\[\[南昌地铁\]\]){0}(?:(、){0})?(?=的)' pattern = (pattern + r'|{0}(?=站厅在|岛式|侧式)').format(single_line) repl = r'\1\2\3\4\5\6\7' return template, pattern, repl def tianjin(): template = '天津地铁线路名' pattern = r'\{\{%s\|M?(Z?\d+)\|\w+\}\}' % template repl = r'{{天津轨道交通线路名|\1|c}}' return template, pattern, repl def chengdu(): template = '成都地铁标志色' pattern = r'\'*<span style="color:#\{\{%s\|\d+\}\}">' pattern = pattern % template + r"'*(.+?)'*</span>'*" repl = r'\1' return template, pattern, repl if __name__ == '__main__': main(DestainBot)
import sys from bot import main if __name__ == "__main__": if len(sys.argv) > 1: chat_id = sys.argv[1] main(chat_id) else: print("please supply chat id")
self.links.pop(n) return s = input(mode + str(n) + ' > ').strip() if mode == 's': self.links[n] = s else: n += 1 if mode == 'a' else 0 self.links.insert(n, s) def _reset_links(self): 'List links in the disambiguation page.' contents = self.disambig_page.text() self.links = re.findall(self.first_link_in_line, contents) self.links.insert(0, self.disambig_page.page_title + '?') def _print_options(self, *pairs): 'Print multiple option items in the menu.' for key, option in pairs: self._print_option(key, option) @staticmethod def _print_option(key, option): 'Print a single option item in the menu.' F = colorama.Fore print('{F.YELLOW}[{key}]{F.RESET} {option}'.format(**locals())) if __name__ == '__main__': main(Disambiguator, argc=3)
import re from bot import Bot, main from replace import ReplaceBot from regex import RegexBot class RegexReplaceBot(RegexBot, ReplaceBot): def __call__(self, pattern, repl, edit_summary, minor=False): 'Search the MediaWiki site with regular expression.' Bot.__call__(self, edit_summary, minor) self.pattern = pattern self.repl = repl for item in self.site.search('insource:/%s/' % pattern): page = self._parse(item) self._evaluate(page) self._show_stat() def _replace(self, page, contents): 'Do regular expression substitute and preview the changes.' result = re.sub(self.pattern, self.repl, contents) if self.minor: # automatic mode self._save(page, result) else: # manual mode self._confirm(page, result) if __name__ == '__main__': main(RegexReplaceBot, argc=4)
prompt = colorama.Fore.YELLOW + self.stations[normalized][1] action = True self._info(page, ' -> ', prompt, end='') if action: self._replace(page, contents, self.stations[normalized], included) def _replace(self, page, contents, data, existing=False): 'Do regular expression substitute and preview the changes.' # remove existing parameters s = contents if existing: fields = '|'.join(self.keywords) s = re.sub(self.field_pattern % fields, '', s) # get the last occurrence for match in re.finditer(self.field_pattern % self.fields, s): pass # insert telegraph code after the match i = match.end() result = ''.join((s[:i], self.repl.format(*data), s[i:])) self._diff(contents, result) self._confirm(page, result, verbose=False) if __name__ == '__main__': main(RailwayBot)
def get_data(url): main(usr, pwd, file_path, url) data, small_data = preprocess_data() return data, small_data
#!/usr/bin/env python import os import sys path0 = os.path.dirname(__file__) path1 = os.path.abspath(os.path.join(path0, os.pardir, os.pardir)) sys.path.insert(0, path1) # We must use this because this file is also called bot.py. #sys.path.append(path1) import bot # RelEng uses bot.py at the original location, this file is a stub to call bot.py at the new place. if __name__ == '__main__': bot.main()
def start_bot(): bot.main()
def test_main(self, start): bot.main() self.assertTrue(start.called)
from creds import TOKEN from bot import main if __name__ == "__main__": main(TOKEN)
def gui(): bot.main()
def main(): ebay.main() bot.main()
#!/usr/bin/env python from bot import main if __name__ == "__main__": main()
def main(): with pid.PidFile(NAME): import bot bot.main()
def home(): st.title("Welcome to Enhancing Virtual Engagement with EVE") bot.main()
class BacklinkBot(Bot): rules = [ (r'({rsrc})', r'{dest}|\1'), (r'(?:{rsrc})\|({rdest})', r'\1'), (r'(?:{rsrc})\|([^\]|]+)', r'{dest}|\1'), ] def __call__(self, title, src, dest, edit_summary, minor=False): 'Iterate through backlinks.' super().__call__(edit_summary, minor) rsrc = '|'.join(map(re.escape, self._dialects(src))) self._replace(self.site.pages[title], rsrc, dest, raw=True) def _replace(self, page, src, dest, raw=False): 'Do regular expression substitute.' rsrc = src if raw else re.escape(src) rdest = re.escape(dest) if dest else '(?!)' # disable the second rule contents = page.text() for pattern, replace in self.rules: pattern = r'\[\[%s\]\]' % pattern.format(**locals()) replace = r'[[%s]]' % replace.format(**locals()) if dest else r'\1' contents = re.sub(pattern, replace, contents) self._save(page, contents, verbose=True) if __name__ == '__main__': main(BacklinkBot, argc=5)
def start(args): bot.main(args)
def main(): scheduler.setup_schedule() threading.Thread(target=scheduler.run_schedule).start() bot.main()
import threading import asyncio import bot import tcp_echo loop = asyncio.get_event_loop() bot_thread = threading.Thread(target=lambda: bot.main(loop)) server_thread = threading.Thread(target=tcp_echo.main) bot_thread.start() server_thread.start() bot_thread.join() server_thread.join()
class RevertBot(Bot): def __call__(self, title, edit_summary, minor=False): 'Fetch the pages.' super().__call__(edit_summary, minor) while True: try: self._replace(self.site.pages[input('> ')]) except EOFError: self._show_stat() sys.exit() except Exception as err: print('{0.__class__.__name__}: {0}'.format(err)) def _replace(self, page): 'Check the edit history and revert to the previous version.' revisions = page.revisions(limit=2, prop='ids|user|content') last_revision = next(revisions) if last_revision['user'] != self.site.username: msg = 'Skip page "{0}" (last revision {1[revid]} by {1[user]}).' print(msg.format(page.name, last_revision)) self.ignored += 1 else: prev_revision = next(revisions) self._save(page, prev_revision['*']) if __name__ == '__main__': main(RevertBot)
sys.exit(2) check_packages() args = sys.argv if '-p' in args: if len(args) < 4: usage() index = args.index('-p') PID = args[index + 1] args.pop(index + 1) args.pop(index) else: PID = bot.PID daemon = MyDaemon(PID) if len(args) == 2 or len(args) == 3: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'check' == sys.argv[1]: cloop = asyncio.get_event_loop() cloop.run_until_complete(bot.main(cloop, notrealy=True)) cloop.close() else: print('Unknown command') sys.exit(2) sys.exit(0) else: usage()
#created by rayane866(rynpix) from flask import Flask, request, jsonify, send_file import json, bot with open("settings.json", "r") as json_file: settings = json.load(json_file) cookie = settings["cookie"] main_groupId = settings["MainGroupId"] log_name = settings["log_name"] max_log_lines = settings["max_log_lines"] bot.main(log_name, max_log_lines, cookie) app = Flask(__name__) @app.route("/bot/rank", methods = ["GET"]) def rank(): if bot.logged: groupid = request.args.get("groupid", type=int) userid = request.args.get("userid", type=int) rank = request.args.get("rank", type=int) if groupid: bot.rank(groupid, userid, rank) elif main_groupId: bot.rank(main_groupId, userid, rank) else: bot.logger.warning("No group id found") else: bot.logger.error(f"invalid cookie: '{cookie}'\n.Try changing your cookie and restarting the server.")
def inline_button_news(update, context): query = update.callback_query query.answer() if query.data == "unsubscribe": unsubscribe_news(update, context) if query.data == "subscribe": subscribe_news(update, context) if query.data == "forward": query.edit_message_reply_markup(get_inline_keyboard(menu2=True)) if query.data == "back": query.edit_message_reply_markup(get_inline_keyboard(menu1=True)) if query.data == "botton1": query.edit_message_text(text="you shose botton1", reply_markup=get_inline_keyboard(menu1=True)) context.bot.send_message( chat_id=update.effective_chat.id, text="hello", reply_markup=get_inline_keyboard(menu2=True), ) if __name__ == "__main__": from bot import main main()
'Iterate through pages transcluding from the template.' super().__call__(edit_summary, minor) self.pattern = pattern self.repl = repl ns = 'Template:' for page in self.site.pages[ns + template].embeddedin(): self._evaluate(page) self._show_stat() def _evaluate(self, page): 'Analyze the page contents to decide the next step.' if page.namespace in [0, 10]: # only articles and templates contents = page.text() if re.search(self.pattern, contents): return self._replace(page, contents) return next(self) def _replace(self, page, contents): 'Do regular expression substitute and preview the changes.' self._info(page) result = re.sub(self.pattern, self.repl, contents) self._diff(contents, result) self._confirm(page, result) if __name__ == '__main__': main(RegexBot, argc=5)