def test_delete_by_name(self):
        print('Testing delete_gif_group_by_id()')

        GifGroupService.delete_gif_group_by_name('test0')
        answer = len(GifGroupService.get_all_gif_groups())

        self.assertEqual(0, answer, 'phrase should be {0} actual {1}'.format(0, answer))
        print('Successful\n')
 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')
    def test_add_new_gif_group_and_get_gif_group_by_id(self):
        print('Testing test_add_new_gif_group() and get_gif_group_by_id()')

        gifGroup = GifGroup(groupId=2, authorId=10101,  createDate='2021-09-08',
                            accessLevel=0, groupType='common', name='test1')
        GifGroupService.add_new_gif_group(gifGroup=GifGroup(authorId=10101, createDate='2021-09-08', name='test1'))
        gifGroup2 = GifGroupService.get_gif_group_by_id(2)

        self._check_data(checking_obj=gifGroup2, control_obj=gifGroup)
        print('Successful\n')
    def test_update_gif_group_phrase(self):
        print('Testing update_gif_group_phrase()')

        gifGroup = GifGroupService.get_gif_group_by_id(1)
        gifGroup.phrase = 'hello'
        GifGroupService.update_gif_group_phrase(gifGroup=gifGroup)
        gifGroup2 = GifGroupService.get_gif_group_by_id(1)

        self._check_data(checking_obj=gifGroup2, control_obj=gifGroup)
        print('Successful\n')
    def test_update_gif_group_access_level(self):
        print('Testing update_gif_group_access_level()')

        gifGroup = GifGroupService.get_gif_group_by_id(1)
        gifGroup.accessLevel = 1
        GifGroupService.update_gif_group_access_level(gifGroup=gifGroup)
        gifGroup2 = GifGroupService.get_gif_group_by_id(1)

        self._check_data(checking_obj=gifGroup2, control_obj=gifGroup)
        print('Successful\n')
    def test_get_all_gif_groups(self):
        print('Testing get_all_gif_groups()')

        answer = len(GifGroupService.get_all_gif_groups())

        self.assertEqual(1, answer, 'phrase should be {0} actual {1}'.format(1, answer))
        print('Successful\n')
    def test_get_gif_group_by_name(self):
        print('Testing get_gif_group_by_name()')

        gifGroup = GifGroupService.get_gif_group_by_name('test0')
        self._check_data(checking_obj=gifGroup,
                         control_obj=GifGroup(groupId=1, authorId=10101,  createDate='2021-09-08',
                                              accessLevel=0, groupType='common', name='test0', phrase='testing0'))
        print('Successful\n')
Beispiel #8
0
async def set_param(ctx: discord.ext.commands.Context, *words):
    try:
        if words[0] not in DBGuilds[ctx.guild.id].__dict__.keys():
            await message.bomb_message(ctx=ctx,
                                       message='Неверное ключевое слово',
                                       type='error')
        else:
            if words[0] in ('maxLinks', 'muteTime', 'personalRolesAllowed'):
                DBGuilds[ctx.guild.id].__dict__[words[0]] = int(words[1])
                GuildService.update_guild_common(guild=DBGuilds[ctx.guild.id])

            elif words[0] in ('banBotFunctions', 'noLinksRoleId',
                              'lightMuteRoleId', 'muteRoleId',
                              'muteVoiceChatRoleId'):
                roleId = messagesProcessing.get_role(ctx=ctx, bufferParts=3).id
                DBGuilds[ctx.guild.id].__dict__[words[0]] = roleId
                GuildService.update_guild_roles(guild=DBGuilds[ctx.guild.id])

            elif words[0] == 'welcomePhrase':
                DBGuilds[ctx.guild.id].__dict__[words[0]] = ' '.join(words[1:])
                GuildService.update_guild_welcome_phrase(
                    guild=DBGuilds[ctx.guild.id])

            elif words[0] == 'welcomeGifGroupId':
                gifGroup: GifGroup.GifGroup = GifGroupService.get_gif_group_by_name(
                    name=words[1])
                DBGuilds[ctx.guild.id].__dict__[words[0]] = gifGroup.groupId
                GuildService.update_welcome_gif_group_id(
                    guild=DBGuilds[ctx.guild.id])

            elif words[0] == 'membersCounterChatId':
                DBGuilds[ctx.guild.id].__dict__[
                    words[0]] = messagesProcessing.get_text_chat_link(
                        ctx=ctx).id
                GuildService.update_guild_chats(guild=DBGuilds[ctx.guild.id])

            else:
                await message.bomb_message(
                    ctx=ctx,
                    message='Данная настройка в данное время недоступна ',
                    type='error')
                return
            await message.bomb_message(
                ctx=ctx, message='Настройка {0} обновлена'.format(words[0]))

    except ValueError as valErr:
        await _dialog.message.bomb_message(ctx=ctx,
                                           message=str(valErr),
                                           type='error')
Beispiel #9
0
async def t(ctx: discord.ext.commands.Context, *words):
    await ctx.message.delete()

    if discord.utils.get(ctx.author.roles,
                         id=DBGuilds[ctx.guild.id].banBotFunctions):
        await _dialog.message.bomb_message(
            ctx=ctx, message='Данная функция вам недоступна', type='error')
        return

    await _dialog.message.log(author=ctx.author,
                              message='вызов команды тригера',
                              ctx=ctx,
                              params=words)
    """-t [комманда] [ключевое слово] [параметры]"""

    try:
        if words[0] == 'help':  # ===== ПОМОЩЬ
            await ctx.send(
                textFileProcessing.RadAll(
                    filename='information/triggers_help.txt'))

        elif words[0] == 'list':  # ===== ЗАПРОС ДАННЫХ О ВСЁМ СПИСКЕ
            gifKeyWords = '\t'.join(
                group.name for group in GifGroupService.get_all_gif_groups())
            await ctx.send(
                f'```Всего gif: {GifService.get_all_gif_count()}'
                f'   всего ключевых слов: {GifGroupService.get_gif_group_count()} \n{gifKeyWords}```'
            )

        elif words[0] == 'new':  # ===== ДОБАВЛЕНИЕ НОВОГО КЛЮЧЕВОГО СЛОВА
            if GifGroupService.is_exist_gif_group_by_name(name=words[1]):
                raise ValueError('данное ключевое слово уже занято')
            newGifGroup = GifGroup.GifGroup(name=words[1].lower(),
                                            authorId=ctx.author.id,
                                            createDate=datetime.strftime(
                                                datetime.now(), "%Y-%m-%d"))
            if len(words) == 2:
                GifGroupService.add_new_gif_group(gifGroup=newGifGroup)
            else:
                newGifGroup.phrase = ' '.join(words[2:])
                GifGroupService.add_new_gif_group_full(gifGroup=newGifGroup)
            await _dialog.message.bomb_message(
                ctx=ctx,
                message='ключевое слово <{0}> создано'.format(
                    newGifGroup.name))

        else:  # ===== ВЫЗОВ GIF
            if words[0] not in ('lock', 'edit', 'rename', 'info', 'add',
                                'DeleteTrigger', 'delete', 'page'):
                gifGroup = GifGroupService.get_gif_group_by_name(name=words[0])
                if len(ctx.message.mentions) > 0:
                    text = '{0} {1} {2}'.format(ctx.author.mention, gifGroup.phrase, ctx.message.mentions[0].mention) \
                        if gifGroup.phrase is not None else ctx.message.mentions[0].mention
                    await ctx.send(text + '\n' +
                                   GifService.get_random_gif_from_group(
                                       groupId=gifGroup.groupId).gifUrl)
                else:
                    if len(words) >= 2 and words[1].isdigit():
                        randomGif = GifService.get_gif(
                            groupId=gifGroup.groupId, index=int(words[1]))
                    else:
                        randomGif = GifService.get_random_gif_from_group(
                            groupId=gifGroup.groupId)
                    await ctx.send(randomGif.gifUrl)
                return

            gifGroup = GifGroupService.get_gif_group_by_name(name=words[1])

            if words[0] == 'info':  # ===== ПОЛУЧЕНИЕ ИНФОРМАЦИИ О ТРИГГЕРЕ
                count = GifService.get_gif_count_by_group_id(
                    groupId=gifGroup.groupId)
                answer = await dataBaseProcessing.print_gif_group(
                    gifGroup=gifGroup, gifCount=count)
                await ctx.send('```{0}```'.format(answer))
                return

            if not (gifGroup.authorId == ctx.author.id or gifGroup.accessLevel
                    == 1 or ctx.author.guild_permissions.administrator):
                raise ValueError('у вас нет прав использовать данную команду')

            if words[0] == 'lock':  # ===== СМЕНА РЕЖИМА ДОСТУПА
                gifGroup.accessLevel = int(not gifGroup.accessLevel)
                GifGroupService.update_gif_group_access_level(
                    gifGroup=gifGroup)

            elif words[0] == 'edit':  # ===== СМЕНА ФРАЗЫ ТРИГГЕРА
                gifGroup.phrase = ' '.join(words[2:])
                GifGroupService.update_gif_group_phrase(gifGroup=gifGroup)
                await _dialog.message.bomb_message(ctx=ctx,
                                                   message='фраза изменена')

            elif words[0] == 'rename':  # ===== ПЕРЕИМЕНОВЫВАЕНИЕ ГРУППЫ
                newName = words[1].lower()
                gifGroup.name = newName
                GifGroupService.update_gif_group(gifGroup=gifGroup)
                await _dialog.message.bomb_message(
                    ctx=ctx, message='ключевое слово изменено')

            elif words[0] == 'add':  # ===== ДОБАВЛЕНИЕ GIF
                gifUrl = await search_gif_mes(ctx=ctx)
                GifService.add_new_gif(
                    gif=Gif.Gif(groupId=gifGroup.groupId, gifUrl=gifUrl))
                await _dialog.message.bomb_message(
                    ctx=ctx, message='добавлено в <{0}>'.format(gifGroup.name))

            elif words[0] == 'page':  # ===== ВЫВОД 10 GIF
                if not words[2].isdigit():
                    raise ValueError('число введено неверно')
                for gifData in GifService.get_gif_page(
                        groupId=gifGroup.groupId, index=int(words[2])):
                    await ctx.send(gifData.gifUrl)

            elif words[0] == 'DeleteTrigger':  # ===== УДАЛЕНИЕ ГРУППЫ
                GifService.delete_all_gif_by_group_id(groupId=gifGroup.groupId)
                GifGroupService.delete_gif_group_by_id(
                    groupId=gifGroup.groupId)
                await _dialog.message.bomb_message(
                    ctx=ctx,
                    message='Ключевое слово <{0}> удалено'.format(
                        gifGroup.name))

            elif words[0] == 'delete':  # ===== УДАЛЕНИЕ GIF
                if not words[2].isdigit():
                    raise ValueError('число введено неверно')
                GifService.delete_gif_by_group_id_and_index(
                    groupId=gifGroup.groupId, index=int(words[2]))
                await _dialog.message.bomb_message(
                    ctx=ctx,
                    message='гиф удалена из <{0}>'.format(gifGroup.name))

    except ValueError as valErr:
        await _dialog.message.bomb_message(ctx=ctx,
                                           message=str(valErr),
                                           type='error')
 def tearDownClass(cls):
     GifGroupService.clear_table()
     UserService.clear_table()
 def setUp(self):
     GifGroupService.clear_table()
     gifGroup = GifGroup(authorId=10101, name='test0', createDate='2021-09-08',
                         groupType='common', phrase='testing0')
     GifGroupService.add_new_gif_group_full(gifGroup=gifGroup)
                   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')

# ========== CONNECTION 2 ===========
GifService.clear_table()
GifGroupService.clear_table()

connection = sql.connect(path2)
cursor = connection.cursor()
print('connected: ' + path2)

# ========== table 1 ===========
cursor.execute(""" SELECT * FROM triggers """)
data = cursor.fetchall()
idDict = {}
i = 1
for row in data:
    newGifGroup = GifGroup(name=row[0],
                           authorId=row[1],
                           phrase=row[2],
                           accessLevel=row[3],