async def voice_stats_update(bot, member: discord.Member,
                             before: discord.VoiceState,
                             after: discord.VoiceState, usersInVoice: dict):
    if before.channel is None:
        usersInVoice[member.id] = time.time()
    if after.channel is None:
        vcTimeCounter = time.time() - usersInVoice.pop(member.id)

        if vcTimeCounter > 10000000:
            await _dialog.message.log(
                bot=bot,
                message='{0} - ошибка вычисления времени в гс чате [{1}]'.
                format(member.name, vcTimeCounter))
        else:
            UserService.append_stats_on_voice_chat2(
                userId=member.id, exp=0, voiceChatTime=vcTimeCounter)
            currDate = datetime.now()
            ActivityLogService.logVoiceChatTime(guildId=member.guild.id,
                                                userId=member.id,
                                                period=currDate.date(),
                                                periodTime=currDate.time(),
                                                chatTime=vcTimeCounter)
            await _dialog.message.log(bot=bot,
                                      message='{0} пробыл в гс {1}сек.'.format(
                                          member.name, vcTimeCounter))
async def delete_exp(MesList):
    defLog: str = ""
    userDict = {}
    # Вычесление удаляемого опыта
    for mes in MesList:
        if mes.author.bot:
            continue

        # Если пользователь попадается впервые, создаётся новый объект
        if mes.author.id not in userDict.keys():
            userDict[mes.author.id] = DBUser(userId=mes.author.id,
                                             symbolsCount=0,
                                             exp=0,
                                             messagesCount=0)

        # Вычисление и запись поинжаемых статистик
        symbolsCount = text_len(mes.content)
        userDict[mes.author.id].symbolsCount -= symbolsCount
        userDict[mes.author.id].exp -= (symbolsCount + 1) / 10
        userDict[mes.author.id].messagesCount -= 1

    # Понижение статистик и логирование
    for authorId in userDict:
        author = userDict[authorId]
        UserService.append_stats_on_messages(user=author)
        defLog += f'\n > {authorId} > удалено: {author.messagesCount} сообщений, ' \
                  f'{author.symbolsCount} символов, {author.exp} опыта'
    return defLog
Ejemplo n.º 3
0
async def on_member_join(member):
    await _dialog.message.log(
        message="пользователь {0} зашёл на сервер {1}".format(
            member.display_name, member.guild.name),
        color='green')

    if DBGuilds[member.guild.id].welcomePhrase is None:
        embed = discord.Embed(colour=discord.colour.Color.green())
        embed.description = "Пользователь {0} присоединился к нам".format(
            member.display_name)
        await member.guild.system_channel.send(embed=embed)

    else:
        await member.guild.system_channel.send('{0} {1}'.format(
            member.mention, DBGuilds[member.guild.id].welcomePhrase))

    if DBGuilds[member.guild.id].welcomeGifGroupId is not None:
        triggerGif = GifService.get_random_gif_from_group(
            DBGuilds[member.guild.id].welcomeGifGroupId)
        await member.guild.system_channel.send(triggerGif.gifUrl)

    await update_counters(member.guild)

    try:
        DBUser = UserService.get_user_by_id(userId=member.id)
    except ValueError:
        UserService.add_new_user(userId=member.id)
        DBUser = UserService.get_user_by_id(userId=member.id)

    await usersProcessing.fix_level_role(
        user=member,
        rolesList=member.guild.roles,
        levelRoleDict=DBGuilds[member.guild.id].levelsMap,
        funcX=get_level_from_exp,
        exp=DBUser.exp)
 def setUpClass(cls):
     UserService.add_new_user(101)
     GifGroupService.add_new_gif_group_full(
         GifGroup(authorId=101,
                  name='test',
                  groupType='common',
                  phrase='testing'))
     print('\n[[[   TESTING GifGroupService   ]]]\n')
Ejemplo n.º 5
0
async def update_levels(ctx: discord.ext.commands.Context):
    global DBGuilds

    i = 0
    for discordUser in ctx.guild.members:
        if discordUser.bot:
            continue
        try:
            DBUser = UserService.get_user_by_id(userId=discordUser.id)
        except ValueError:
            UserService.add_new_user(userId=discordUser.id)
            await _dialog.message.log(
                message=
                f'[{ctx.guild.name}] Обнаружен пользователь {discordUser.name} ',
                color='yellow')
            DBUser = UserService.get_user_by_id(userId=discordUser.id)
        oldLevel = DBUser.level
        DBUser.level = get_level_from_exp(exp=DBUser.exp)
        newLevel = DBUser.level
        if oldLevel < newLevel:
            i += 1
        UserService.update_user(user=DBUser)
        await usersProcessing.fix_level_role(
            user=discordUser,
            rolesList=ctx.guild.roles,
            levelRoleDict=DBGuilds[ctx.guild.id].levelsMap,
            funcX=get_level_from_exp,
            exp=DBUser.exp)

    await _dialog.message.bomb_message(ctx=ctx,
                                       message=f'обновлено пользователей {i}')
Ejemplo n.º 6
0
    def setUpClass(cls):
        GuildUserService.clear_table()
        UserService.clear_table()
        GuildService.clear_table()

        GuildService.add_new_guild(guildId=101)
        GuildService.add_new_guild(guildId=102)
        GuildService.add_new_guild(guildId=103)

        UserService.add_new_user(userId=11)
        UserService.add_new_user(userId=12)
        UserService.add_new_user(userId=13)

        print('\n[[[   TESTING GuildMemberService   ]]]\n')
async def calc_all_stats_after_time(guild: discord.Guild, time: datetime,
                                    spamChannelsId: list) -> str:
    print(guild.name)
    userDict = {}

    for channel in guild.channels:
        if issubclass(type(channel), discord.TextChannel):
            isSpamChannel = True if channel.id in spamChannelsId else False

            async for message in channel.history(limit=10000,
                                                 oldest_first=False,
                                                 after=time):
                if message.author.bot:
                    continue

                if message.author.id not in userDict.keys():
                    userDict[message.author.id] = User(
                        userId=message.author.id,
                        messagesCount=0,
                        symbolsCount=0)

                userDict[message.author.id].messagesCount += 1
                textLen = messagesProcessing.text_len(stroke=message.content)
                userDict[message.author.id].symbolsCount += textLen

                if isSpamChannel:
                    ActivityLogService.logOneSpamMessage(
                        guildId=guild.id,
                        userId=message.author.id,
                        period=message.created_at.date(),
                        symbolsCount=textLen)
                else:
                    ActivityLogService.logOneMessage(
                        guildId=guild.id,
                        userId=message.author.id,
                        period=message.created_at.date(),
                        symbolsCount=textLen)

    answerLog = [
        '[Поиск сообщений после последней записи на сервере {0}]'.format(
            guild.name)
    ]

    for keyID in userDict:
        userDict[keyID].exp = (userDict[keyID].symbolsCount +
                               userDict[keyID].messagesCount) / 10

        try:
            UserService.append_stats_on_messages(user=userDict[keyID])

        except Exception:
            answerLog.append(' > новый пользователь:')
            UserService.add_new_user(userId=keyID)
            UserService.append_stats_on_messages(user=userDict[keyID])

        answerLog.append('\t> {0} > сообщений: {1}, символов: {2}'
                         ''.format(keyID, userDict[keyID].messagesCount,
                                   userDict[keyID].symbolsCount))

    return '\n'.join(answerLog)
Ejemplo n.º 8
0
async def level(ctx, *words):
    await ctx.message.delete()
    await _dialog.message.log(author=ctx.author,
                              message='вызов проверки уровня',
                              ctx=ctx,
                              params=words)

    targetUser = ctx.message.mentions[0] if len(
        ctx.message.mentions) > 0 else ctx.author
    print(f'targetUser: {targetUser}')

    DBUser = UserService.get_user_by_id(userId=targetUser.id)
    DBUser.exp = exp_from_stats2(UStats=DBUser)
    DBUser.level = get_level_from_exp(exp=DBUser.exp)
    UserService.update_user(user=DBUser)

    await usersProcessing.fix_level_role(
        user=targetUser,
        rolesList=ctx.guild.roles,
        levelRoleDict=DBGuilds[ctx.guild.id].levelsMap,
        funcX=get_level_from_exp,
        exp=DBUser.exp)
Ejemplo n.º 9
0
async def exp(ctx: discord.ext.commands.Context, *words):
    try:
        if not (words[0].isdigit() or words[0][1:].isdigit()):
            raise ValueError('число введено неверно')
        expChanging = int(words[0])

        discordUser = messagesProcessing.get_user_link(ctx=ctx)
        UserService.add_user_exp_modifier2(userId=discordUser.id,
                                           exp=expChanging,
                                           expModifier=expChanging)
        # Это вставка из -level для уточнения уровняы
        DBUser = UserService.get_user_by_id(userId=discordUser.id)
        DBUser.exp = exp_from_stats2(UStats=DBUser)
        DBUser.level = get_level_from_exp(exp=DBUser.exp)
        UserService.update_user(user=DBUser)

        text = 'бонус к опыту выдан' if expChanging >= 0 else 'штраф к опыту выдан'
        await _dialog.message.bomb_message(ctx=ctx, message=text)
    except ValueError as valErr:
        await _dialog.message.bomb_message(ctx=ctx,
                                           message=str(valErr),
                                           type='error')
    def setUpClass(cls):
        QuestionService.clear_table()
        UserService.clear_table()

        UserService.add_new_user(userId=11)
        UserService.add_new_user(userId=12)

        print('\n[[[   TESTING QuestionService  ]]]\n')
Ejemplo n.º 11
0
async def check_level_and_role(discordUser, discordGuild, levelRoleDict, funcX, checkAllRoles: bool = False):
    updated = False
    # Получение пользователя из БД
    try:
        DBUser = UserService.get_user_by_id(userId=discordUser.id)
    except ValueError:
        UserService.add_new_user(userId=discordUser.id)
        await _dialog.message.log(message=f'[{discordGuild.name}] Обнаружен пользователь {discordUser.name} ',
                                  color='yellow')
        DBUser = UserService.get_user_by_id(userId=discordUser.id)

    # Сверка уровня
    oldLevel = DBUser.level
    DBUser.level = funcX(exp=DBUser.exp)
    newLevel = DBUser.level
    if oldLevel != newLevel:
        UserService.update_user(user=DBUser)
        updated = True

    if not updated and not checkAllRoles and newLevel not in levelRoleDict:
        return updated


    # Получение роли, соответсвующей уровню
    roleLevel = 0
    for levelKey in levelRoleDict.keys():
        if levelKey <= newLevel:
            roleLevel = levelKey
        else:
            break

    # Поиск и удаление предыдущей роли за уровни
    if not checkAllRoles:
        newRoleIndex = levelRoleDict.keys().index(roleLevel)

        if newRoleIndex > 0:
            oldRoleIndex = levelRoleDict.keys().index(newRoleIndex - 1)
            answer = discord.utils.get(discordUser.roles, id=levelRoleDict[oldRoleIndex])

            if answer is not None:
                await discordUser.remove_roles(answer)
    # Удаление всех возможных ролей за уровни
    else:
        for levelKey in levelRoleDict.keys():
            answer = discord.utils.get(discordUser.roles, id=levelRoleDict[levelKey])

            if answer is not None:
                await discordUser.remove_roles(answer)

    if roleLevel in levelRoleDict.keys():
        await discordUser.add_roles(discord.utils.get(discordGuild.roles, id=levelRoleDict[roleLevel]))
def user_stat_embed(ctx, funcX) -> discord.Embed:
    user: discord.abc.User = ctx.message.mentions[0] if len(
        ctx.message.mentions) > 0 else ctx.author
    DBUSer: User = UserService.get_user_by_id(userId=user.id)
    nextLevelExp = funcX(DBUSer.level + 1)
    emb: discord.Embed = discord.Embed(
        color=discord.colour.Color.dark_magenta(),
        title='Пользователь {0}:'.format(user.display_name))
    emb.set_thumbnail(url=user.avatar_url)
    emb.add_field(name='Уровень:', value=str(DBUSer.level))
    emb.add_field(name='Опыт:',
                  value='{0}/{1}'.format(round(DBUSer.exp, 1), nextLevelExp))
    if DBUSer.expModifier != 0:
        fieldName = 'Бонус к опыту:' if DBUSer.expModifier > 0 else 'Штраф к опыту:'
        emb.add_field(name=fieldName, value=str(DBUSer.expModifier))
    emb.add_field(name='Статистика:',
                  value='Отправлено сообщений: {0}\nНапечатано символов: {1}\
    \nВремя в голосовых чатах:{2}'.format(
                      DBUSer.messagesCount, DBUSer.symbolsCount,
                      time.strftime("%dд::%H:%M:%S",
                                    time.gmtime(DBUSer.voiceChatTime)).replace(
                                        ' ', '')),
                  inline=False)
    return emb
 def setUpClass(cls):
     UserService.add_new_user(10101)
     print('\n[[[   TESTING GifGroupService   ]]]\n')
basePath = str(botdb)
basePath = basePath.split("'")[-2]
path1 = basePath.split('\\\\')[:-1] + ['transfer'] + ['botdata.db']
path1 = '\\\\'.join(path1)
path2 = basePath.split('\\\\')[:-1] + ['transfer'] + ['gif_triggers.db']
path2 = '\\\\'.join(path2)

# ========== CONNECTION 1 ===========
connection = sql.connect(path1)
cursor = connection.cursor()
print('connected: ' + path1)

cursor.execute(""" SELECT * FROM userstats """)
data = cursor.fetchall()

UserService.clear_table()
for row in data:
    newUser = User(userId=row[0],
                   exp=row[1],
                   level=row[2],
                   messagesCount=row[3],
                   symbolsCount=row[4],
                   voiceChatTime=row[5])
    newUser.voluteCount = 0
    newUser.expModifier = 0
    UserService.add_new_user(userId=newUser.userId)
    UserService.update_user(user=newUser)

print('data copied')
connection.close()
print('connection closed')
Ejemplo n.º 15
0
async def on_message(mes: discord.Message):
    if mes.author.bot:
        return
    if mes.content.count('@') > DBGuilds[mes.guild.id].maxLinks:
        await mes.delete()
        await mes.channel.send(
            '```удалено сообщение с недопустимым количеством упоминаний```')
        await _dialog.message.log(
            message=
            'канал: {0}, пользователь: {1}][удалено сообщение с недопустимым'
            'количеством упоминаний'.format(mes.author.name, mes.channel.name))
        return
    count = messagesProcessing.text_len(mes.content)

    if (mes.channel.id in DBGuilds[mes.guild.id].spamChannels):

        ActivityLogService.logOneSpamMessage(guildId=mes.guild.id,
                                             userId=mes.author.id,
                                             period=datetime.now().date(),
                                             symbolsCount=count)
        # Пуск команд
        try:
            await asyncio.wait_for(bot.process_commands(message=mes),
                                   timeout=DBGeneralSettings.timeUntilTimeout)
        except asyncio.TimeoutError:
            await mes.channel.send('```timeout```')
        return

    # Проверка уровня
    if UserService.append_stats_on_messages_with_level_check(
            userId=mes.author.id,
            mesCount=1,
            symbolsCount=count,
            exp=(count + 1) / 10,
            funcX=get_level_from_exp):
        DBUser = UserService.get_user_by_id(userId=mes.author.id)
        DBUser.level = get_level_from_exp(exp=DBUser.exp)
        UserService.update_user(user=DBUser)

        if DBUser.Level in DBGuilds[mes.guild.id].levelsMap.keys():
            await usersProcessing.fix_level_role(
                user=mes.author,
                rolesList=mes.guild.roles,
                levelRoleDict=DBGuilds[mes.guild.id].levelsMap,
                funcX=get_level_from_exp,
                exp=DBUser.exp)
        await _dialog.message.bomb_message2(
            mes=mes,
            text=f'{mes.author.name} '
            f'получил(а) новый уровень - {DBUser.Level}!',
            type='error')

    ActivityLogService.logOneMessage(guildId=mes.guild.id,
                                     userId=mes.author.id,
                                     period=datetime.now().date(),
                                     symbolsCount=count)

    # Пуск команд
    try:
        await asyncio.wait_for(bot.process_commands(message=mes),
                               timeout=DBGeneralSettings.timeUntilTimeout)
    except asyncio.TimeoutError:
        await mes.channel.send('```timeout```')
 def tearDownClass(cls):
     GifGroupService.clear_table()
     UserService.clear_table()
Ejemplo n.º 17
0
 def tearDownClass(cls):
     UserVoiceChatService.clear_table()
     UserService.clear_table()
Ejemplo n.º 18
0
 def tearDownClass(cls):
     GuildUserService.clear_table()
     UserService.clear_table()
     GuildService.clear_table()
Ejemplo n.º 19
0
 def setUpClass(cls):
     UserService.add_new_user(101)
     print('\n[[[   TESTING UserVoiceChatService  ]]]\n')