Beispiel #1
0
    def message(self, update, context, anon=False):
        message = update.message
        level = self.get_level(message.chat.id)
        if anon:
            message.chat.first_name = "anonymous"
        if level > 0:
            text = message.text
            time = message.date.astimezone(self.tzone).strftime(self.fmt)
            image = None

            try:
                if message.document != None:  # image is document
                    imageFile = context.bot.get_file(message.document.file_id)
                elif message.sticker != None:
                    if (message.sticker.is_animated):
                        message.reply_text("Cannot print animated stickers...")
                        return  # don't attempt to download anything
                    else:
                        # Get sticker
                        imageFile = context.bot.get_file(message.sticker.file_id)
                elif message.photo != None:
                    imageFile = context.bot.get_file(message.photo[-1].file_id)
                image = imageFile.download(f"./fcache/{imageFile.file_unique_id}.jpeg")
                text = message.caption

                img = Image.open(image)
                width, height = img.size
                maxwidth = self.bprinter.p.profile.media['width']['pixels']
                resizeratio = maxwidth/width
                img = img.resize((maxwidth, int(height * resizeratio)))
                img.save(f"./fcache/{imageFile.file_unique_id}.png", 'PNG')
                self.users.update(tdbop.increment("images"), Query().id == message.chat.id)
            except (IndexError, AttributeError):
                pass

            self.users.update(tdbop.increment("messages"), Query().id == message.chat.id)
            if text is not None:
                newvalue = self.users.search(Query().id == message.chat.id)[0]['characters'] + len(text)
                self.users.update(tdbop.set("characters", newvalue), Query().id == message.chat.id)

            if level < 2:  # don't print additional info for admins
                text = f"Om {time} zei {message.chat.first_name}\n{text}"

            self.printq.insert({"name": message.chat.first_name,
                                "id": message.chat.id,
                                "date": time,
                                "text": text,
                                "image": image,
                                "printed": False})

            if self.sleep:
                message.reply_text("The printer is currently asleep, your receipt was queued and will be printed when the printer wakes up")
            else:
                # trigger printer
                self.bprinter.brrr(context)
def change_word_count(user_id, increase):
    S = Query()
    if increase:
        db.update(increment("word_count"), S.user_id == user_id)
    else:
        db.update(decrement("word_count"), S.user_id == user_id)
    return db.search(S.user_id == user_id)[0]
Beispiel #3
0
 async def on_reaction_add(self, reaction, user):
     if reaction.emoji == "👍":
         if reaction.message.id in self.streepjes_messages.keys():
             if user.id == self.streepjes_messages[reaction.message.id][1]:
                 await reaction.remove(user)
             elif reaction.count == 3:
                 if reaction.message.id in self.streepjes_messages.keys():
                     if not self.db.search(
                             self.User.name == self.streepjes_messages[
                                 reaction.message.id][0]):
                         self.db.insert({
                             'name':
                             self.streepjes_messages[reaction.message.id]
                             [0],
                             'streepjes':
                             1
                         })
                     else:
                         self.db.update(
                             increment('streepjes'),
                             self.User.name == self.streepjes_messages[
                                 reaction.message.id][0])
                     await reaction.message.channel.send(
                         "{} now has {} streepje(s)".format(
                             self.bot.get_user(self.streepjes_messages[
                                 reaction.message.id][0]).name,
                             self.db.search(
                                 self.User.name == self.streepjes_messages[
                                     reaction.message.id][0])[0]
                             ['streepjes']))
def change_word_count(user_id, increase):
    S = Query()
    if increase:
        db.update(increment("word_count"), S.user_id == user_id)
    else:
        db.update(decrement("word_count"), S.user_id == user_id)
    return db.search(S.user_id == user_id)[0]
Beispiel #5
0
 def add_object(self, data):
     """
     Attempt to insert a data object into the store. If it does not exist, it gets initialized. Otherwise the
     statistics are updated by increasing the receive count and the time of the last reception if the message has
     not been flagged as deleted.
     :param data: data object to store
     """
     idx = hash_string(data)
     now = int(time.time())
     with self.lock:
         Stats = Query()
         res = self.stats.search(Stats.idx == idx)
         if len(res) == 0:
             self.data.insert({'idx': idx, 'content': data})
             self.stats.insert({'idx': idx,
                                'first_seen': now,
                                'receive_count': 0,
                                'send_count': 0,
                                'last_received': None,
                                'last_sent': None,
                                'deleted': False})
             log_debug("Data object created: {}".format(data))
         else:
             deleted = res[0]['deleted']
             if deleted:
                 log_debug("Received deleted data object: {}".format(data))
             self.stats.update({'last_received': now}, Stats.idx == idx)
             self.stats.update(increment('receive_count'), Stats.idx == idx)
             log_debug("Data object updated: {}".format(data))
    def AjouterBonTravail(self, id_equipement, dictio):
        # Ajout du bon de travail dans la base de données
        conf = self._getConf()
        db = self._getDB()
        db_equip = self._getEquipDB()
        Equipement = Query()
        list_ajout_champ_equipement = list(conf['BDT_Ajout_Champ_Equipement'])   # récupère la liste des informations à ajouter dans le dictionnaire
        dict_renvoi = {'Reussite': False}                       # Initialisation du dictionnaire de renvoie
        dict_equipement = db_equip.get(Equipement['ID'] == id_equipement)  # récupère l'équipement via la BDD des équipements
        id_bdt = self._ObtenirProchainIDdeBDT(id_equipement)    # id du nouveau bon de travail

        if id_bdt == -1:                                        # Equipement non existant
            print("The equipment doesn't exist. ID :", id_equipement)
            return dict_renvoi
        elif self._verifierChamps(dictio, conf) and self._verifierDict(dictio, conf):   # Vérification du dictionnaire
            dictio['ID-EQ'] = str(id_equipement)
            dictio['ID-BDT'] = str(id_bdt)
            for key, value in dict_equipement.items():     # récupère les infos pertinentes et les ajoute au dictionnaire du bon de travail
                if key in list_ajout_champ_equipement:
                    dictio[key] = value
            print(dictio)
            if db.insert(dictio) != list([]):                   # ajout du nouveau bdt dans la db
                # Mise à jour du nombre de bons de travail pour cet équipement dans la base de données des équipements
                Equipement = Query()
                db_equip.update(increment('NbBonTravail'), Equipement['ID'] == id_equipement)
                dict_renvoi['Reussite'] = True                  # Ajout réalisé
                self._ActualiserConfiguration(conf)                 # Actualisation du fichier conf
        else:
            print('An error occured')
        
        return dict_renvoi
Beispiel #7
0
def old_picture(bot, update, args):
    if args:
        user_input = "-".join(args)
        parsed_user_input = parse(user_input)
        user_input_string = str(parsed_user_input) 

        year = user_input_string[0:4]
        month = user_input_string[5:7]
        day = user_input_string[8:10]

        start_date = date(1995, 6, 16)

        entered_date = date(int(year), int(month), int(day))

        end = (datetime.now(est_timezone) - timedelta(1)).strftime(date_fmt)
        end_date = date(int(end[0:4]), int(end[5:7]), int(end[8:10]))

        old_pictures_url = f'https://api.nasa.gov/planetary/apod?api_key={config.api_key}&date={year}-{month}-{day}'
        old_picture_data = requests.get(old_pictures_url).json()

        if start_date <= entered_date <= end_date:

            if old_potd_db.contains(Query()['chat_id'] == update.message.chat_id):

                old_picture_user = Query()
                result = old_potd_db.search((old_picture_user.chat_id == update.message.chat_id) & (old_picture_user.time != str(0)))
                time_getter = [sub['time'] for sub in result]
                print(time_getter[0])

                old_time = datetime.strptime(str(time_getter[0]), fmt)
                current_time = datetime.strptime(str(datetime.now(est_timezone).strftime(fmt)), fmt)

                # Calculate how much time has passed since we served the image
                minutes_diff = (current_time - old_time).total_seconds() / 60.0

                if int(minutes_diff) >= 0:
                    old_potd_db.upsert({'time': str(datetime.now(est_timezone).strftime(fmt)), 'username': str(update.message.from_user.username)}, Query()['chat_id'] == update.message.chat_id)
                    old_potd_db.update(increment('count'), Query()['chat_id'] == update.message.chat_id)

                    check_api_data_and_send_info(bot, update, update.message.chat_id, old_picture_data['media_type'], old_picture_data['title'], old_picture_data['url'], old_picture_data['explanation'], randomize_date = 100, is_old_picture = True)

                else:
                    bot.send_message(chat_id = update.message.chat_id, text = f"You're doing that too much. Please try again in {2 - int(minutes_diff)} minute(s)!")
                    print(f"User {update.message.chat_id} and ID {str(update.message.from_user.username)} spammed the /old_picture command and hit a cooldown!")

            else:
                old_potd_db.insert({'chat_id': update.message.chat_id, 'time': str(datetime.now(est_timezone).strftime(fmt)), 'username': update.message.from_user.username, 'count': 1})

                check_api_data_and_send_info(bot, update, update.message.chat_id, old_picture_data['media_type'], old_picture_data['title'], old_picture_data['url'], old_picture_data['explanation'], randomize_date = 100, is_old_picture = True)
            
        else:
            bot.send_message(chat_id = update.message.chat_id, text = f"Only dates between 16 June 1995 and {(datetime.now(est_timezone) - timedelta(1)).strftime('%d %B %Y')} are supported. Please try again!")
    else:
        start_date = date(1995, 6, 16)
        end = (datetime.now(est_timezone) - timedelta(1)).strftime(date_fmt)
        end_date = date(int(end[0:4]), int(end[5:7]), int(end[8:10]))
        randomize_date = fake.date_between(start_date = start_date, end_date = end_date).strftime('%d %B %Y')
        
        bot.send_message(chat_id = update.message.chat_id, text = f"Please enter a date after the command! For example: <code>/old_picture {randomize_date} </code>", parse_mode = 'HTML')
Beispiel #8
0
def confirm_user(username):
	usr = users.search(where('username') == username)
	if usr and (len(usr) == 1):
		if usr[0]["confirmed"] == 0:
			users.update(increment('confirmed'), where('username') == username)
			print("Confirmed value: " + str(usr[0]['confirmed']))
		return True
	return False
 def auto_increate_item_id() -> int:
     # 生成自增编号
     # base初始化时,会插入一条带有item_id_auto字段的doc,用作自增编号
     # 主要用于视频工作项的全局生成序号
     DB.db_.table(__base_table__).update_auto_id(
         increment('item_id_auto'),
         where('item_id_auto').exists())
     return DB.get_last_item_id()
Beispiel #10
0
    def increment_number(self) -> int:
        """Incrament current comic number by one

        :return: increased number
        :rtype: int
        """
        self.meta.update(increment("number"), doc_ids=[self.number_id])
        return self.get_settings()["number"]
Beispiel #11
0
 def add_spammer(self, user_id):
     user = self.db_user.table('user')
     qry = Query()
     result = user.get(qry.user_id == user_id)
     if not result:
         user.insert({'user_id': user_id, 'report_count': 0, 'spam_count': 1, 'point_earned' : 0, 'point_used': 0})
     else:
         user.update(increment('spam_count'), eids=[result.eid])
Beispiel #12
0
def add_stars(top_poster):
    db = TinyDB('./db.json')
    User = Query()
    if top_poster is not None:
        for poster in top_poster[0]:
            if db.contains(User.uid == poster):
                db.update(increment('stars'), User.uid == poster)
            else:
                db.insert({'uid': poster, 'stars': 1})
Beispiel #13
0
    async def on_message(self, message):

        if message.author.bot:
            return

        channel = self.bot.get_channel(818817278912626718)

        if not message.channel == channel:
            return

        if "h:" in message.content:
            return

        if '' in message.content:
            db.update(increment('age'), User.name == message.author.id)
            money.update(increment('money'), User.name == message.author.id)

            await self.bot.process_commands(message)
Beispiel #14
0
def record_command_usage(command, N=2):
    LOGGER.info(f'Incrementing stat for command usage {command} with N={N}')
    command_parts = command.split()
    for i in range(min(len(command_parts), N)):
        command_prefix = ' '.join(command_parts[:i + 1])
        stat_search = CMD_DB.get(CMD.command == command_prefix)
        if not stat_search:
            CMD_DB.insert({'command': command_prefix, 'count': 1})
        else:
            CMD_DB.update(increment('count'), CMD.command == command_prefix)
Beispiel #15
0
def main(bot, author_id, message, thread_id, thread_type, **kwargs):
    command = first_word_of(message)
    plugins = bot.plugins
    if not is_command(command, plugins):
        return
    stat_search = CMD_DB.get(CMD.command == command)
    if not stat_search:
        CMD_DB.insert({'command': command, 'count': 1})
    else:
        CMD_DB.update(increment('count'), CMD.command == command)
Beispiel #16
0
def failed(name, package):
    if db.search(where('name') == name and where('package') == package):
        db.update(increment('failed'),
                  where('name') == name and where('package') == package)
    else:
        db.insert({
            'package': package,
            'name': name,
            'skipped': 0,
            'failed': 1
        })
Beispiel #17
0
async def strike(context):
	usr = context.message.mentions[0]
	if db.contains(Users.id ==usr.id):
			if db.contains((Users.id == usr.id) & (Users.swears == 2)):
				await bot.kick(usr)
				db.update({'swears': 0}, Users.id ==usr.id)
			else:
				db.update(increment('swears'), Users.id == usr.id)
	else:
		db.insert({'id': usr.id, 'swears': 0})
	await bot.send_message(usr,"You have recived a strike if you recive three strikes you will be kicked")
Beispiel #18
0
    def process_by_week(self, log_date):
        log_week = log_date.isocalendar()[1]
        log_year = log_date.year

        found = self.db_week.search((q.year == log_year) & (q.week == log_week))

        if not found:
            self.db_week.insert({'week': log_week, 'year': log_year, 'total': 1})
        else:
            self.db_week.update(increment('total'), ((q.year == log_year) & (q.week == log_week)))

        self.db_week.close()
Beispiel #19
0
    def process_by_month(self, log_date):
        log_month = log_date.month
        log_year = log_date.year

        found = self.db_month.search((q.year == log_year) & (q.month == log_month))

        if not found:
            self.db_month.insert({'month': log_month, 'year': log_year, 'total': 1})
        else:
            self.db_month.update(increment('total'), ((q.year == log_year) & (q.month == log_month)))

        self.db_month.close()
Beispiel #20
0
async def on_message(message):
	if profanity.contains_profanity(message.content):
		await bot.delete_message(message)
		if db.contains(Users.id == message.author.id):
			if db.contains((Users.id == message.author.id) & (Users.swears == 2)):
				await bot.kick(message.author)
				db.update({'swears': 0}, Users.id == message.author.id)
			else:
				db.update(increment('swears'), Users.id == message.author.id)
		else:
			db.insert({'id': message.author.id, 'swears': 0})
		await bot.send_message(message.author,"You have recived a strike if you recive three strikes you will be kicked")
Beispiel #21
0
    def AjouterBonTravail(self, id_equipement, dictio):
        # Ajout du bon de travail dans la base de données
        db = TinyDB(self._pathname, storage=YAMLStorage)        # data base des bons de travail
        id_bdt = self._ObtenirProchainIDdeBDT(id_equipement)    # id du nouveau bon de travail
        dictio['ID-EQ'] = id_equipement
        dictio['ID-BDT'] = id_bdt
        db.insert(dictio)                                       # ajout du nouveau bdt dans la db

        # Mise à jour du nombre de bons de travail pour cet équipement dans la base de données des équipements
        db_equip = TinyDB(self._equip_pathname, storage=YAMLStorage)
        Equipement = Query()
        db_equip.update(increment('Nombre de bons de travail'), Equipement['ID'] == id_equipement)
Beispiel #22
0
async def on_message_edit(before, after):
	message = after
	if profanity.contains_profanity(message.content):
		await bot.delete_message(message)
		if db.contains(Users.id == message.author.id):
			if db.contains((Users.id == message.author.id) & (Users.swears == 2)):
				await bot.kick(message.author)
				db.update({'swears': 0}, Users.id == message.author.id)
			else:
				db.update(increment('swears'), Users.id == message.author.id)
		else:
			db.insert({'id': message.author.id, 'swears': 0})
		await bot.send_message(message.author,"Don't curse, bitch. You have 2 more chances.")
Beispiel #23
0
def pictureoftheday_message(bot, update):
    
    start_time = time.time()

    start_date = date(1995, 6, 16)
    end = (datetime.now(est_timezone) - timedelta(1)).strftime(date_fmt)
    end_date = date(int(end[0:4]), int(end[5:7]), int(end[8:10]))

    randomize_date = fake.date_between(start_date = start_date, end_date = end_date).strftime('%d %B %Y')

    nasa_data = requests.get(nasa_url).json()

    '''
    If user doesn't exist, go to the else loop and populate data into db

    If user_id EXISTs in the db, check the time and extract minute difference
    '''
    if main_potd_db.contains(Query()['chat_id'] == update.message.chat_id):

        user = Query()
        result = main_potd_db.search((user.chat_id == update.message.chat_id) & (user.time != str(0)))
        time_getter = [x['time'] for x in result]
        print(time_getter[0])

        old_time = datetime.strptime(str(time_getter[0]), fmt)
        current_time = datetime.strptime(str(datetime.now(est_timezone).strftime(fmt)), fmt)

        # Calculate how much time has passed since we served the image
        minutes_diff = (current_time - old_time).total_seconds() / 60.0
            
        # If more than 10 minutes have passed, they can reuse the command
        if int(minutes_diff) >= 0:
            main_potd_db.upsert({'time': str(datetime.now(est_timezone).strftime(fmt)), 'username': str(update.message.from_user.username), 'command_banner_shown': False}, Query()['chat_id'] == update.message.chat_id)
            main_potd_db.update(increment('count'), Query()['chat_id'] == update.message.chat_id)

            check_api_data_and_send_info(bot, update, update.message.chat_id, nasa_data['media_type'], nasa_data['title'], nasa_data['url'], nasa_data['explanation'], randomize_date = randomize_date, is_old_picture = False)
        
        else:
            bot.send_message(chat_id = update.message.chat_id, text = f"You're doing that too much. Please try again in {10 - int(minutes_diff)} minute(s)!")
            print(f"User {update.message.chat_id} and ID {str(update.message.from_user.username)} spammed the /picture command and hit a cooldown!")

    # A new user has invoked the picture command since the chat_id cannot be found in database
    else:
        main_potd_db.insert({'chat_id': update.message.chat_id, 'time': str(datetime.now(est_timezone).strftime(fmt)), 'username': update.message.from_user.username, 'count': 1, 'command_banner_shown': True})

        check_api_data_and_send_info(bot, update, update.message.chat_id, nasa_data['media_type'], nasa_data['title'], nasa_data['url'], nasa_data['explanation'], randomize_date = randomize_date, is_old_picture = False)

    print(f"{time.time() - start_time} seconds")
Beispiel #24
0
    def get(self, name):
        project = db.get(Query().name == name)

        build_path = '{}/.penkins/builds/{}'.format(os.path.expanduser('~'),
                                                    name)

        if not os.path.exists(build_path):
            os.mkdir(build_path)
        builds_db = '{}/builds.json'.format(build_path)

        dbbuils = TinyDB('{}/builds.json'.format(build_path))

        if os.path.exists(builds_db):
            dbbuils.insert({'counter': 0})

        dbbuils.update(increment('counter'))

        build_id = dbbuils.get(Query().counter).get('counter')

        if os.path.exists('{}/{}'.format(build_path, build_id)):
            os.rmdir('{}/{}'.format(build_path, build_id))
        if not os.path.exists('{}/{}'.format(build_path, build_id)):
            os.mkdir('{}/{}'.format(build_path, build_id))
            os.mkdir('{}/{}/build'.format(build_path, build_id))

        if project.get('vcs') == "git":
            g1 = git.Git('{}/{}/build/'.format(build_path, build_id))
            g1.clone(project.get('repository'), '.')

        # Read .penkins-ci.yml file
        # https://docs.gitlab.com/ee/ci/yaml/
        if os.path.exists('{}/{}/build/.penkins.yml'.format(
                build_path, build_id)):
            pc = PenkinsConfig('{}/{}/build/.penkins.yml'.format(
                build_path, build_id)).config
            # print(pc)
            # scripts
            for cmd in pc.get('script'):
                # print('{}/{}/build/'.format(build_path, build_id))
                # print(cmd)
                # print(cmd.split(' '))
                subprocess.call(cmd,
                                cwd='{}/{}/build/'.format(
                                    build_path, build_id),
                                shell=True)
        return {'project_name': name}
Beispiel #25
0
def user_points_upsert(user_id, incrdecr):
    User_data = Query()
    points = db_user_data.search(User_data.id == user_id)
    if len(points) > 0 and incrdecr == 'incr':
        db_user_data.update(operations.increment('point_amount'),
                            User_data.id == user_id)
    elif len(points) > 0 and incrdecr == 'decr':
        db_user_data.update(operations.decrement('point_amount'),
                            User_data.id == user_id)
    else:
        db_user_data.insert({
            'id': user_id,
            'point_amount': 1,
            'warnings': [],
            'mutes': [],
            'bans': []
        })
Beispiel #26
0
def buy_stock(account, clip):
    # deduct the cost
    db.update(subtract('bucks', STOCK_COST),
              (where('type') == 'account') & (where('id') == account['id']))
    # purchase the stock
    if len(
            db.update(increment('shares'),
                      (where('type') == 'stock') & (where('clip') == clip) &
                      (where('user_id') == account['id']))) == 0:
        db.insert({
            'type': 'stock',
            'user_id': account['id'],
            'disp_name': account['name'],
            'clip': clip,
            'shares': 1,
            'total_payout': 0
        })
Beispiel #27
0
    def _insert_product(self, product, mutant):
        product_code = _gen_product_code(product)

        has_product_code = len(
            self.db.search(Query().product_code == product_code)) > 0

        self.state.db.update(increment('product_versions'),
                             Query().type == 'config')

        if has_product_code:
            self.db.update(append('mutants', _mutant_dict(mutant)),
                           Query().product_code == product_code)

        else:
            self.db.insert({
                'product_code': product_code,
                'features': product,
                'mutants': [_mutant_dict(mutant)]
            })
Beispiel #28
0
 def get_data(self):
     """
     Retrieve the data objects sorted by increasing popularity, namely in increasing receive_count, then send_count
     and finally the last time they were sent by the current aDTN node.
     :return: data objects sorted by increasing popularity.
     """
     with self.lock:
         Stats = Query()
         stats = self.stats.search(Stats.deleted == False)
         res = sorted(stats, key=lambda x: (x['receive_count'], x['send_count'], x['last_sent']))[:10]
         now = int(time.time())
         objects = []
         for r in res:
             idx = r['idx']
             Objects = Query()
             obj = self.data.search(Objects.idx == idx)[0]['content']
             objects.append(obj)
             self.stats.update({'last_sent': now}, Objects.idx == idx)
             self.stats.update(increment('send_count'), Objects.idx == idx)
     return objects
Beispiel #29
0
async def on_raw_reaction_add(payload):
    if payload.user_id == client.user.id:
        return

    member_role_ids = list(map(lambda role: str(role.id),
                               payload.member.roles))

    if STAFF_ID not in member_role_ids:
        print("someone reacted, but they're not staff")
        return

    query = Query()
    pen = pending.search(query.message_id == payload.message_id)[0]

    if str(payload.emoji) == "👍":
        pending.remove(where('message_id') == payload.message_id)
        users.update(where('name') == pen['user'], increment('rank'))
    elif (str(payload.emoji) == "👎"):
        print("thumbsdown from mod")
        pending.remove(where('message_id') == payload.message_id)
    else:
        print(payload.emoji)
Beispiel #30
0
    async def acceptduel(self, context):
        """Accept a duel."""

        BaseCog.check_main_server(self, context)
        BaseCog.check_bot_channel(self, context)
        BaseCog.check_forbidden_characters(self, context)

        economy = BaseCog.load_dependency(self, 'Economy')
        main_db = economy.main_db
        stats = BaseCog.load_dependency(self, 'Stats')
        trivia_table = stats.trivia_table
        gambling = BaseCog.load_dependency(self, 'Gambling')
        weapon_emotes = gambling.weapon_emotes

        if not context.message.author.name in [
                d[1] for d in self.duels.values()
        ]:
            await self.bot.post_error(
                context, 'You have not been challenged to a duel, ' +
                context.message.author.name + '.')
        elif context.message.author.name in [
                d[0] for d in self.duels.values()
        ]:
            await self.bot.post_error(
                context,
                'You have already challenged someone else to a duel, ' +
                context.message.author.name +
                ', you need to finish that duel before you can start another one.'
            )
        else:
            challenger = None
            bet = None
            duel_id = None

            for did, (c, user, b, accepted) in self.duels.items():
                if user == context.message.author.name and not accepted:
                    challenger = c
                    bet = b
                    duel_id = did
                    break

            if challenger is None:
                await self.bot.post_error(
                    context, 'You have not been challenged to a duel, ' +
                    context.message.author.name + '.')
                return

            user_balance = main_db.get(
                self.bot.query.user == context.message.author.name)['balance']
            other_balance = main_db.get(
                self.bot.query.user == challenger)['balance']

            if other_balance < bet:
                await self.bot.post_message(
                    self.bot.bot_channel,
                    '**[DUEL]** ' + challenger + ' doesn\'t even have ' +
                    str(bet) + ' ' + config.currency_name +
                    's anymore, the duel has been canceled.')
                del self.duels[duel_id]
            elif user_balance < bet:
                await self.bot.post_message(
                    self.bot.bot_channel,
                    '**[DUEL]** You do not have enough ' +
                    config.currency_name + 's, ' +
                    context.message.author.name + '. ' + challenger +
                    ' wants to fight over ' + str(bet) + ' ' +
                    config.currency_name + 's and your current balance is ' +
                    str(user_balance) + '.')
                del self.duels[duel_id]
            else:
                self.duels[duel_id] = (challenger, context.message.author.name,
                                       bet, True)

                try:
                    main_db.update(subtract('balance', bet),
                                   self.bot.query.user == challenger)
                    main_db.update(
                        subtract('balance', bet),
                        self.bot.query.user == context.message.author.name)
                    main_db.update(subtract('gambling_profit', bet),
                                   self.bot.query.user == challenger)
                    main_db.update(
                        subtract('gambling_profit', bet),
                        self.bot.query.user == context.message.author.name)
                except Exception as e:
                    await self.bot.post_error(
                        context,
                        'A fatal error occurred while trying to subtract ' +
                        config.currency_name +
                        's from respective accounts. Duel is canceled and balances might be wrong.',
                        config.additional_error_message)
                    log.exception(e)
                else:
                    try:
                        await self.bot.post_message(
                            self.bot.bot_channel,
                            '**[DUEL]** Ladies and gentlemen, we are about to see a duel to the death between '
                            + challenger + ' and ' +
                            context.message.author.name +
                            '. Who is going to prevail, taking ' + str(bet) +
                            ' ' + config.currency_name +
                            's from their opponent?')
                        await asyncio.sleep(
                            self.duel_battle_delay
                        )  # nothing happens during this time
                        duel_participants = []
                        duel_participants.append(context.message.author.name)
                        duel_participants.append(challenger)

                        # Choose winners
                        first = random.choice(duel_participants)
                        second = ''

                        if first == context.message.author.name:
                            second = challenger
                        else:
                            second = context.message.author.name

                        balance_first = 0

                        try:
                            balance_first = main_db.get(
                                self.bot.query.user == first)['balance']
                            main_db.update(
                                {'balance': balance_first + bet + bet},
                                self.bot.query.user == first)
                        except Exception as e:
                            await self.bot.post_error(
                                context,
                                'A fatal error occurred while trying to add ' +
                                config.currency_name + 's to ' + first +
                                '\'s account. Balances might be wrong.',
                                config.additional_error_message)
                            log.exception(e)
                        else:
                            weapon = random.choice(weapon_emotes)
                            await self.bot.post_message(
                                self.bot.bot_channel, '**[DUEL]** ' + first +
                                ' ' + weapon + ' ' + second)

                            try:
                                gambling_profit_first = main_db.get(
                                    self.bot.query.user ==
                                    first)['gambling_profit']
                                main_db.update(
                                    {
                                        'gambling_profit':
                                        gambling_profit_first + bet + bet
                                    }, self.bot.query.user == first)

                                first_total_won_duels = main_db.get(
                                    self.bot.query.user ==
                                    first)['duel_winnings']
                                main_db.update(
                                    {
                                        'duel_winnings':
                                        first_total_won_duels + bet
                                    }, self.bot.query.user == first)
                                highest_total_owned = trivia_table.get(
                                    self.bot.query.name ==
                                    'highest_total_owned')['value']

                                if balance_first + bet > highest_total_owned:
                                    trivia_table.update(
                                        {
                                            'value':
                                            balance_first + bet,
                                            'person1':
                                            first,
                                            'person2':
                                            'None',
                                            'date':
                                            datetime.datetime.now().strftime(
                                                "%Y-%m-%d %H:%M")
                                        }, self.bot.query.name ==
                                        'highest_total_owned')
                            except Exception as e:
                                await self.bot.post_error(
                                    context,
                                    'Could not update some stats (affects !trivia output).',
                                    config.additional_error_message)
                                log.exception(e)

                            try:
                                main_db.update(increment('duel_wins'),
                                               self.bot.query.user == first)

                                highest_duel = trivia_table.get(
                                    self.bot.query.name ==
                                    'highest_duel')['value']

                                if bet > highest_duel:
                                    trivia_table.update(
                                        {
                                            'value':
                                            bet,
                                            'person1':
                                            first,
                                            'person2':
                                            second,
                                            'date':
                                            datetime.datetime.now().strftime(
                                                "%Y-%m-%d %H:%M")
                                        },
                                        self.bot.query.name == 'highest_duel')
                            except Exception as e:
                                await self.bot.post_error(
                                    context,
                                    'Could not update some duel stats (affects !trivia output).',
                                    config.additional_error_message)
                                log.exception(e)

                            try:
                                main_db.update(increment('duels'),
                                               self.bot.query.user == first)
                                main_db.update(increment('duels'),
                                               self.bot.query.user == second)
                                trivia_table.update(
                                    increment('value'),
                                    self.bot.query.name == 'amnt_duels')
                            except Exception as e:
                                await self.bot.post_error(
                                    context,
                                    'Could not update some duel stats (affects !trivia output).',
                                    config.additional_error_message)
                                log.exception(e)
                    except Exception as e:
                        await self.bot.post_error(
                            context,
                            'Oh no, something went wrong (duel may or may not have finished).',
                            config.additional_error_message)
                        log.exception(e)

                del self.duels[duel_id]
Beispiel #31
0
def Call(Keywords, AuctionOnly, Page, MaxPrice, MinPrice, Present):
    Retries = 5  # Number of call attempts before giving up
    SleepTime = 1  # Time between failed calls (doubles each time)

    global LogPosition  # If no call folder exists then create a new one
    if LogPosition == None: New()

    # Database where number of call are recorded
    dbCallCount = TinyDB(
        os.path.dirname(os.path.dirname(__file__)) + "/DataBase/CallCount")
    Search = Query()

    try:  # Get previous call time from data base
        CallTime = dbCallCount.table("_default").all()[
            len(dbCallCount.table("_default").all()) - 1]['Time']
    except:  # Unable to get call time from data base
        CurrentTime = int(time.mktime(datetime.now().timetuple()))
        dbCallCount.insert({
            'Calls': 0,
            'Time': CurrentTime
        })  # Add call time to data base
        CallTime = CurrentTime

    CurrentDateTime = int(time.mktime(
        datetime.now().timetuple()))  # Current time
    # Time when calls reset
    NewCallingPerioud = int(
        time.mktime(
            datetime.utcfromtimestamp(int(CallTime) + 60 * 60 * 16 -
                                      60 * 5).replace(hour=1).replace(
                                          minute=5).replace(second=0).replace(
                                              microsecond=0).timetuple()))

    if (
            CurrentDateTime > NewCallingPerioud
    ):  # If we have passed time when calls reset then were in a new call region
        print("New Time Region")
        CurrentTime = int(time.mktime(datetime.now().timetuple()))
        dbCallCount.insert({
            'Calls': 0,
            'Time': CurrentTime
        })  # Insert new entry with no calls
        CallTime = CurrentTime

    # Note calls reset 1am mtd, or 8am utc

    if Present == 1:  # Find current items
        OperationName = 'findItemsByKeywords'
    else:  # Find completed items
        OperationName = "findCompletedItems"

    APICALL = 'https://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=' + str(OperationName) + \
              '&SERVICE-VERSION=1.0.0' \
              '&SECURITY-APPNAME=' + str(SecurityAppName) +  \
              '&RESPONSE-DATA-FORMAT=JSON' \
              '&REST-PAYLOAD' \
              '&keywords=' + str(Keywords) + \
              '&paginationInput.pageNumber=' + str(Page)

    ItemFilterCount = 0
    APICALL = APICALL + \
              '&itemFilter(' + str(ItemFilterCount) + ').name=MaxPrice' \
              '&itemFilter(' + str(ItemFilterCount) + ').value=' + str(MaxPrice) + \
              '&itemFilter(' + str(ItemFilterCount + 1) + ').name=MinPrice' \
              '&itemFilter(' + str(ItemFilterCount + 1) + ').value=' + str(MinPrice)
    ItemFilterCount = ItemFilterCount + 2

    if AuctionOnly == 1:
        APICALL = APICALL + \
                  '&itemFilter(' + str(ItemFilterCount) + ').name=ListingType'\
                  '&itemFilter(' + str(ItemFilterCount) + ').value(0)=AuctionWithBIN' \
                  '&itemFilter(' + str(ItemFilterCount) + ').value(1)=Auction'

    APICALL = APICALL + '&outputSelector=PictureURLSuperSize'  # Request high quality photo

    for retryNumber in range(Retries):  # Number of attempts
        try:
            report = requests.get(APICALL)  # Call API

            if 'HTTP 404 Not Found' in str(report.json()):  # Connection Error
                time.sleep(SleepTime)
                SleepTime = SleepTime * 2  # Exponential backoff and recall
                continue

            # Save report to location
            ReportSaveLocation = LogPosition + str(time.time()) + ".txt"
            with open(ReportSaveLocation, 'w') as APIResponcefile:
                json.dump(report.json(), APIResponcefile)
            APIResponcefile.close()

            Logs.Write("Search Ebay: " + str(Keywords) + " Page: " +
                       str(Page) + " Auction: " + str(AuctionOnly) +
                       " Present: " + str(Present) + " Between " +
                       str(MinPrice) + " and " + str(MaxPrice) + " at " +
                       str(ReportSaveLocation))

            dbCallCount.update(increment("Calls"),
                               Search.Time == CallTime)  # Incriment Call Count

            return (report.json())  # Success
        except:
            time.sleep(
                SleepTime
            )  # If failed to parce data recall with Exponential backoff
            SleepTime = SleepTime * 2

    print("Failed to get api responce")  # ran out of recall attempts
    Logs.Write("Search Ebay Failed: " + str(Keywords) + " Page: " + str(Page) +
               " Auction: " + str(AuctionOnly) + " Present: " + str(Present) +
               " Between " + str(MinPrice) + " and " + str(MaxPrice))
    return None  # Failure
Beispiel #32
0
 def increment_views(self, table, iid):
     table = self.table(table)
     table.update(increment("views"), self.query.id == iid)
     return table.get(self.query.id == iid)
Beispiel #33
0
Datei: main.py Projekt: nifo/dmu
def get_article(uuid):
    """Get article with a specific uuid."""
    article = db.get(where("uuid") == uuid)
    db.update(increment("read_count"), where("uuid") == uuid)
    db.update(popularity(uuid), where("uuid") == uuid)
    return jsonify(article)
Beispiel #34
0
def test_increment(db):
    db.update(increment('int'), where('char') == 'a')
    assert db.get(where('char') == 'a')['int'] == 2
Beispiel #35
0
def test_increment_with_delta(db):
    db.update(increment('int', 9), where('char') == 'a')
    assert db.get(where('char') == 'a')['int'] == 10