Esempio n. 1
0
async def main():
    try:
        conn = db.get_conn()
        cur = conn.cursor()
        if check_cache(conn):
            print('即将更新缓存,速度较慢,请耐心等待')
            free_game = steam.get_free_games(False)
            cache_game = db.get_cache_game(cur, False)

            new_game = check_appids(free_game, cache_game)
            db.add_cache_game(cur, new_game)
            db.set_status(cur, 'update', int(time()))
            print('缓存更新完成')
            conn.commit()
        else:
            print('使用缓存数据')
            free_game = db.get_cache_game(cur, False)
        cur.close()

        bots = get_cfg('bot')['bot_name']
        for i, bot in enumerate(bots, 1):
            print(f'进度{i}/{len(bots)} 机器人 {bot}')
            await process_bot(conn, bot, free_game)

        cur = conn.cursor()
        count = db.get_status('added')
        cur.close()
        conn.close()
        print(f'总计添加 {count} 个免费游戏')
        print('运行结束')
    except Exception as e:
        print('运行出错')
        print(e)
        traceback.print_stack()
        input('按回车键退出……')
Esempio n. 2
0
    def run(self):
        db.set_status(1)
        util.clear_log()
        util.log("current cookie : " + COOKIE)
        for source in db.source_list():
            util.log("source " + source['name'] + " started")
            url = "http://weixin.sogou.com/weixin?type=1&s_from=input&query=" + source['source'] + "&ie=utf8"

            # search result page
            profile_url = ''
            times = 0
            while True:
                if db.get_status() != 1:
                    util.log("stopped!")
                    db.set_status(0)
                    return

                # the cookie could be out of date
                res = util.request(url, {'Cookie': COOKIE})
                if res is None:
                    break

                soup = BeautifulSoup(res.text, 'lxml')
                profile = soup.select_one('.img-box a')
                if profile is not None:
                    profile_url = profile.attrs['href']
                    break
                times = util.sleep_and_open(url, 'verify search url', times)

            # news profile page
            data = {}
            times = 0
            while True:
                if db.get_status() != 1:
                    util.log("stopped!")
                    db.set_status(0)
                    return

                res = util.request(profile_url)
                if res is None:
                    break

                matches = re.findall(r'var msgList = (.*);', res.text)
                if len(matches) > 0:
                    data = json.loads(matches[0])
                    break
                times = util.sleep_and_open(profile_url, 'verify profile url', times)

            if len(data) > 0:
                self.save(data, source)

        event.after_crawler_finished()
        db.set_status(0)
        util.log("done!")
Esempio n. 3
0
    def hook(d):
        if d['status'] == 'finished':
            donwloadInfo = db.set_status(key, 'finished')
        else:
            donwloadInfo = db.set_download_info(key, d)

        def nothing(n):
            pass

        eel.updateDownloads(donwloadInfo)(nothing)
Esempio n. 4
0
async def process_bot(conn: db.sqlite3.Connection, bot: str, free_game: list):
    cur = conn.cursor()
    db_owned = db.get_owned_game(cur, bot)
    cur.close()

    not_owned = check_appids(free_game, db_owned)
    v_owned, v_not_owned = await asf_api.check_owned_game(bot, not_owned)
    cur = conn.cursor()
    db.add_owned_game(cur, bot, v_owned)
    conn.commit()
    cur.close()

    await asf_api.add_free_game(bot, v_not_owned)
    succ_owned, _ = await asf_api.check_owned_game(bot, v_not_owned)
    cur = conn.cursor()
    db.add_owned_game(cur, bot, succ_owned)
    count = db.get_status(cur, 'added')
    db.set_status(cur, 'added', count + len(succ_owned))
    conn.commit()
    cur.close()
Esempio n. 5
0
def download(key):
    queue = db.get_queue_by_key(key)
    if not queue:
        return
    db.set_status(key, 'downloading')
    url = queue['url']

    def hook(d):
        if d['status'] == 'finished':
            donwloadInfo = db.set_status(key, 'finished')
        else:
            donwloadInfo = db.set_download_info(key, d)

        def nothing(n):
            pass

        eel.updateDownloads(donwloadInfo)(nothing)

    opts = {'progress_hooks': [hook]}
    with youtube_dl.YoutubeDL(opts) as ydl:
        ydl.download([url])
Esempio n. 6
0
def RunSubmission(id):
  # Base info from DB
  # Already filled in the main loop -- Vimal
  lang = langs[id].lower()
  ext = extensions[lang].lower()
  problem = probNames[id]
  user = users[id]

  sourceFile = "%s/submissions/%s/%s/%s.%s" % (BASE, user, id, problem, ext)

  # Compile
  exeFile = "%s/submissions/%s/%s/%s.exe" % (BASE, user, id, problem)
  if lang in needCompile:
    compileLog = "%s/submissions/%s/%s/%s.compile" % (BASE, user, id, problem)
    compileCmd = CompileCommand(sourceFile, exeFile, compileLog, lang)
    
    (out, ret) = Execute(compileCmd)
    compileSuccess = False

    if ret == None:
      compileSuccess = True
    if not compileSuccess:
      print "Error compiling %s" % id
      U(user, int(problem), "CE ")
      compileOutput = ""
      if os.path.exists(compileLog):
        c = open(compileLog, 'r')
        compileOutput = c.read()
      #update in db
      
      # Added by Vimal
      # Update in db that the submisssion compilation failed
      
      db.set_status(id, 'CE', '-', compileOutput)
      return

  #Execute with stdin
  testInput = "%s/problems/%s/INP" % (BASE, problem)
  Output = "%s/submissions/%s/%s/%s.out" % (BASE, user, id, problem)
  Error = "%s/submissions/%s/%s/%s.err" % (BASE, user, id, problem)
  exeCmd = ExecuteCommand(exeFile, testInput, Output, Error, lang, problem)
  (out, ret) = Execute(exeCmd)
  executionSuccess = False
  status = ParseZSimpleOutput(Error)
  # print id, status
  if ret != None:
    print "Error executing %s" % id
    if status['return'] == "tle":
      U(user,int(problem),"TLE")
    else:
      U(user,int(problem),"XE")
    #update db about error

    # Updating, -- Vimal
    stat = ''
    if status['return'] == 'tle':
      stat = 'TLE'
    else:
      stat = 'XE'

    # Dont set any error/score information 
    db.set_status(id, stat)

    return

  if "return" in status:
    if status['return'] == 'ok':
      # update db about time
      executionSuccess = True
      # Update DB -- Vimal
      time = status['time']
      db.update_time(id, time)

    else:
      # update in db about error
      U(user,int(problem),"XE ")
      print status['return']
  else:
    # internal error, put blame on user
    # update db about error
    U(user,int(problem),"IE ")
    print "Internal error %s" % id

    # Update DB -- Vimal
    db.set_status(id, 'IE')
    #db.revert_last_submit(id)

    return

  if not executionSuccess:
    print "Error executing %s" % id
    U(user,int(problem),"XE ")
    #update db about error
    # Update DB -- Vimal
    db.set_status(id, 'XE')
    return

  # Check out with answer
  correctOutput = "%s/problems/%s/OUT" % (BASE, problem)

  if problem !=7:
        checkCmd = "diff -w -bB %s %s 1>/dev/null 2>&1" % (Output, correctOutput)
        (out, ret) = Execute(checkCmd)
        if ret == None:
          # accepted
          # update db
          print "Accepted %s" % id
          # Update DB -- Vimal
          # AC
          points = db.get_problem_points(problem)
          db.set_status(id, 'AC', points)
          db.update_score(problem, id, points)
          # update the score, in the logs
          U(user,int(problem),"AC ")
        else:
          # wrong answer
          # update db
          print "Wrong answer %s" % id
          # Update DB -- Vimal
          # WA
          db.set_status(id, 'WA')
          U(user,int(problem),"WA ")
                                                                                                    
  else:
    ########################################
    #  This section is for the NP-Complete contest #
    #  WE NEED TO GET THIS DONE :)         #
    ########################################  
    # Do we need the correct output for this problem? -- No!
    checkCmd = "%s/problems/%s/checker %s %s"\
                % (BASE, problem, correctOutput, Output)
    (out, ret) = Execute(checkCmd)
    if ret == None:
      out = string.strip(out)
      # out is score
      # update db
      # update-score iff the previous score < current-score
      # but increase the number of submissions anyway
      if out == "WA":
        # Put Wrong Answer
        print "Wrong answer %s" % id
        # Update DB -- Vimal
        # WA
        db.set_status(id, 'WA')
        U(user,int(problem),"WA ")
                                                
      else:
        points = db.get_problem_points(problem)
        db.set_status(id, 'AC', points)
        db.update_score(problem, id, points)
        # update the score, in the logs
        U(user,int(problem),"AC ")
        
    else:
      #internal error
      #update db
      print "Internal Error %s" % id
      U(user,int(problem),"IE ")
      
      # Update DB -- Vimal
      db.set_status(id, 'IE')
Esempio n. 7
0
def set_status(status_string):
    db.set_status('trainer', status_string)
Esempio n. 8
0
def set_status(status_string, secondary=False):
    status_id = 'sec_worker' if secondary else 'worker'
    db.set_status(status_id, status_string)
Esempio n. 9
0
def query_handler(call):
    if call.message:
        if call.data == "check_pay":
            s = requests.Session()
            s.headers['authorization'] = 'Bearer ' + cfg.QIWI_token
            parameters = {'rows': '10'}
            h = s.get('https://edge.qiwi.com/payment-history/v1/persons/' +
                      cfg.QIWI_NUM + '/payments',
                      params=parameters)
            s = parameters
            req = json.loads(h.text)
            for i in range(len(req['data'])):
                if req['data'][i]['comment'] == str(
                        call.message.chat.id) + "-sms":
                    if req['data'][i]['sum']['amount'] == int(cfg.AMOUNT):
                        db.set_sub_status(call.message.chat.id)
                        bot.send_message(call.message.chat.id,
                                         "Доступ получен✅",
                                         reply_markup=keyboard.home_keyboard)
        elif call.data == "cancel":
            bot.send_message(call.message.chat.id, "Отмена❌")
            db.set_sms_bomber_status(call.message.chat.id, "NONE", "NONE")
        elif call.data == "users":
            check_admin = db.get_info_admin()
            if str(call.message.chat.id) in check_admin:
                count = db.count_users()
                bot.send_message(call.message.chat.id,
                                 "Всего пользователей: " + str(count),
                                 reply_markup=keyboard.admin_panel)
            else:
                bot.send_message(call.message.chat.id, "Доступ запрещён!")
        elif call.data == "admins":
            bot.edit_message_text("Выберите действие:",
                                  call.message.chat.id,
                                  call.message.message_id,
                                  reply_markup=keyboard.admin_panel_admins)
        elif call.data == "admins_list":
            count = db.count_admins()
            bot.send_message(call.message.chat.id,
                             "Всего админов: <code>" + str(count[0]) +
                             "</code>\n\n<u>Список:</u> \n<b>" +
                             str(count[1]) + "</b>\n\nТвой user_id: <code>" +
                             str(call.message.chat.id) + "</code>",
                             parse_mode="html",
                             reply_markup=keyboard.admin_panel_admins)
        elif call.data == "add_admin":
            check_admin = db.get_info_admin()
            if str(call.message.chat.id) in check_admin:
                db.set_status(call.message.chat.id, "add_admin")
                bot.edit_message_text(
                    "Введите <b>user_id</b> пользователя:",
                    call.message.chat.id,
                    call.message.message_id,
                    reply_markup=keyboard.cancel_keyboard_adm,
                    parse_mode="html")
            else:
                bot.send_message(call.message.chat.id, "Доступ запрещён!")
        elif call.data == "remove_admin":
            check_admin = db.get_info_admin()
            if str(call.message.chat.id) in check_admin:
                db.set_status(call.message.chat.id, "remove_admin")
                bot.edit_message_text(
                    "Введите <b>user_id</b> пользователя:",
                    call.message.chat.id,
                    call.message.message_id,
                    reply_markup=keyboard.cancel_keyboard_adm,
                    parse_mode="html")
            else:
                bot.send_message(call.message.chat.id, "Доступ запрещён!")
        elif call.data == "mailing":
            check_admin = db.get_info_admin()
            if str(call.message.chat.id) in check_admin:
                db.set_status(call.message.chat.id, "mailing")
                bot.edit_message_text(
                    "Рассылыку получат все!\nВведите текст рассылки:",
                    call.message.chat.id,
                    call.message.message_id,
                    reply_markup=keyboard.cancel_keyboard_adm)
            else:
                bot.send_message(call.message.chat.id, "Доступ запрещён!")
        elif call.data == "cancel_adm":
            bot.send_message(call.message.chat.id,
                             "Отмена❌",
                             reply_markup=keyboard.admin_panel)
            db.set_status(call.message.chat.id, 1)
        elif call.data == "give_acces":
            check_admin = db.get_info_admin()
            if str(call.message.chat.id) in check_admin:
                bot.edit_message_text(
                    "Введите <b>user_id</b> пользователя которому хотите выдать доступ:",
                    call.message.chat.id,
                    call.message.message_id,
                    reply_markup=keyboard.cancel_keyboard_adm,
                    parse_mode="html")
                db.set_status(call.message.chat.id, "give_acces")
            else:
                bot.send_message(call.message.chat.id, "Доступ запрещён!")
Esempio n. 10
0
def message_handler(message):
    if message.text:
        sms_status = db.get_sms_bomber_status(message.chat.id)
        status = db.add_to_database(message.chat.id)
        if sms_status[0] == 1:
            if message.text[0:3] == "380" and len(
                    message.text) == 12 or message.text[0:2] == "79" and len(
                        message.text) == 11:
                db.add_sms_bomber_status(message.chat.id)
                db.set_sms_bomber_status(message.chat.id, 2, message.text)
                bot.send_message(
                    message.chat.id,
                    "Введите время <b>*в секундах*</b> на которое хотите оставить спам:",
                    parse_mode="html",
                    reply_markup=keyboard.cancel_keyboard)
            else:
                bot.send_message(message.chat.id,
                                 "Вы ввели неправельный номер!",
                                 reply_markup=keyboard.cancel_keyboard)
        elif sms_status[0] == 2:
            seconds = list(range(1, 1801))
            try:
                if int(message.text) in seconds:
                    threading.Thread(target=bomber.bomber,
                                     args=(message.chat.id, message.text,
                                           sms_status[1])).start()
                    db.set_sms_bomber_status(message.chat.id, "NONE", "NONE")
                else:
                    bot.send_message(
                        message.chat.id,
                        "Вы можете оставить спам от 1 до 1800 секунд!")
            except:
                bot.send_message(
                    message.chat.id,
                    "Вы можете оставить спам от 1 до 1800 секунд!")
        elif status[0] == "add_admin":
            res = db.get_info_admin()
            if str(message.text) in res:
                bot.send_message(
                    message.chat.id,
                    "Админ уже есть в списке!\nВведите другой <b>user_id!</b>",
                    parse_mode="html",
                    reply_markup=keyboard.cancel_keyboard_adm)
            else:
                db.action_with_admin("add", message.text)
                db.set_status(message.chat.id, 1)
                bot.send_message(message.chat.id,
                                 "Готово!",
                                 reply_markup=keyboard.admin_panel_admins)

        elif status[0] == "remove_admin":
            res = db.get_info_admin()
            if str(message.text) in res:
                if message.text == str(message.chat.id):
                    bot.send_message(
                        message.chat.id,
                        "Вы не можете удалить самого себя!\nВведите другой <b>user_id</b>!",
                        reply_markup=keyboard.cancel_keyboard_adm,
                        parse_mode="html")
                else:
                    db.action_with_admin("remove", message.text)
                    db.set_status(message.chat.id, 1)
                    bot.send_message(message.chat.id,
                                     "Готово!",
                                     reply_markup=keyboard.admin_panel_admins)
            else:
                bot.send_message(
                    message.chat.id,
                    "Админ отстутствует!\nВведите другой <b>user_id</b>!",
                    parse_mode="html",
                    reply_markup=keyboard.cancel_keyboard_adm)
        elif status[0] == "mailing":
            threading.Thread(target=db.mailing,
                             args=(message.chat.id, message.text)).start()
            bot.send_message(message.chat.id, "Рассылка начата!")
            db.set_status(message.chat.id, 1)
        elif status[0] == "give_acces":
            try:
                bot.send_message(
                    message.text,
                    "Вам был выдан доступ к боту🥳\n\nНажмите 👉🏻<b>/start</b>👈🏻 если меню не появилось!",
                    parse_mode="html",
                    reply_markup=keyboard.home_keyboard)
                db.set_sub_status(message.text)
                bot.send_message(message.chat.id,
                                 "Готово!",
                                 reply_markup=keyboard.admin_panel)
                db.set_status(message.chat.id, 0)
            except:
                bot.send_message(
                    message.chat.id,
                    "Ошибка!\n\nВозможно такого пользователя нет в базе данных!",
                    reply_markup=keyboard.cancel_keyboard_adm)
        else:
            if message.text == "/start":
                if status[0] == 1:
                    bot.send_message(
                        message.chat.id,
                        "<code>Добро пожаловать!</code>\n\nЕсли кнопки управления не появились нажмите👉🏻<b>/start</b>👈🏻",
                        parse_mode="html",
                        reply_markup=keyboard.home_keyboard)
                else:
                    buy_keyboard = keyboard.buy_keyboard()
                    bot.send_message(
                        message.chat.id,
                        "Для приобретения доступа к боту воспользуйтесь меню!\n\nЕсли меню не появилось нажмите 👉🏻<b>/start</b>👈🏻",
                        reply_markup=buy_keyboard,
                        parse_mode="html")
            elif message.text == "/get_my_id":
                bot.send_message(message.chat.id,
                                 "Твой user_id: <code>" +
                                 str(message.chat.id) + "</code>",
                                 parse_mode="html")
            elif message.text == "/adm":
                info = db.get_info_admin()
                if str(message.chat.id) in info:
                    bot.send_message(message.chat.id,
                                     "Доступ получен!",
                                     reply_markup=keyboard.admin_panel)
                else:
                    bot.send_message(message.chat.id, "Доступ запрещён!")
            elif "Получить доступ" in message.text:
                buy_keyboard_inline = keyboard.buy_keyboard_inline(
                    message.chat.id)
                bot.send_message(
                    message.chat.id,
                    "1️⃣ Для получения доступа к боту нажмите на кнопку "
                    "<code>\"Оплатить\"</code> снизу👇(Открывать через браузер, "
                    "<u><b>НЕ ЧЕРЕЗ ПРИЛОЖЕНИЕ</b></u>) и подтверждайте платёж! ("
                    "<u><b>менять поля не нужно, всё уже указано</b></u>)\n\n2️⃣ После "
                    "оплаты возращайтесь в бота и нажмите на кнопку <code>\"Проверить "
                    "оплату\"</code> и если вы всё сделали правильно бот автоматически "
                    "выдаст вам доступ!",
                    parse_mode="html",
                    reply_markup=buy_keyboard_inline)
            elif message.text == "ℹ️Помощь":
                emoji = "❤🧡💛💚💙💜🖤"
                random_emoji = random.choice(emoji)
                bot.send_message(
                    message.chat.id,
                    random_emoji +
                    " Смс отправляются с более чем 40 разных сайтов (49 сервисов)\n\n"
                    + random_emoji +
                    " Доступ к боту выдается <code>навсегда</code>\n\n" +
                    random_emoji + " Одновременный спам на 3 номера\n\n" +
                    random_emoji +
                    " Полная анонимность при использовании\n\n\n" +
                    random_emoji + " Цена - <code>" + cfg.AMOUNT +
                    "</code>р\n\nПо всем вопросам обращаться в лс:\n" +
                    cfg.operator,
                    parse_mode="html")
            elif message.text == "Бомбер 📨":
                count = db.get_count_attack(message.chat.id)
                if status[0] == 1:
                    if count >= 3:
                        bot.send_message(
                            message.chat.id,
                            "Вы не можете делать больше 3 атак одновременно!")
                    else:
                        db.add_sms_bomber_status(message.chat.id)
                        bot.send_message(
                            message.chat.id,
                            "Введите номер без + в формате:\n🇺🇦 380xxxxxxxxx\n🇷🇺 79xxxxxxxxx",
                            reply_markup=keyboard.cancel_keyboard)
                else:
                    bot.send_message(message.chat.id, "Доступ запрещён!")
            elif message.text == "Руководство 🧾":
                bot.send_message(
                    message.chat.id,
                    "После покупки доступа к боту у вас появится новое меню под полем для ввода!\n\n1) Нажмите на кнопку <code>\"Бомбер 📨\"</code>\n2) Введите номер вашей жертвы(формат ввода будет приведён в сообщении от бота)\n3) Введите время <code>в секундах</code> на которое хотите оставить спам!\n4) Готово!\n\n<u>Бот оповестит вас когда спам начнётся и закончится!</u>",
                    parse_mode="html")
            else:
                if status[0] == 1:
                    bot.send_message(
                        message.chat.id,
                        "<code>Добро пожаловать!</code>\n\nЕсли кнопки управления не появились нажмите👉🏻<b>/start</b>👈🏻",
                        parse_mode="html",
                        reply_markup=keyboard.home_keyboard)
                else:
                    buy_keyboard = keyboard.buy_keyboard()
                    bot.send_message(
                        message.chat.id,
                        "Для приобретения доступа к боту воспользуйтесь меню!\n\nЕсли меню не появилось нажмите 👉🏻<b>/start</b>👈🏻",
                        parse_mode="html",
                        reply_markup=buy_keyboard)