コード例 #1
0
ファイル: serv.py プロジェクト: sunic3/flex-bot
 async def now_(self, ctx):
     channel_check(ctx)
     await ctx.message.delete()
     d = data_read(ctx.guild)
     d['now'] = not d['now']
     data_write(ctx.guild, d)
     await ctx.send(f'Настройка `сейчас играет` изменена на  [ {int(d["now"])} ]  :thumbsup:', delete_after=20)
コード例 #2
0
 async def on_guild_join(self, guild):
     info = discord.utils.find(
         lambda x: x.permissions_for(guild.me).send_messages,
         guild.text_channels)
     embed = discord.Embed(
         colour=discord.Colour.green(),
         title=f'Приветик, {guild.name}:heart_exclamation:',
         description=
         f'Спасибочки за приглашение на свой сервер, {guild.owner.mention} '
         f':revolving_hearts:\nВ основном, я выполняю функции музыкального бота. '
         f'Напиши `.m.h` чтобы посмотреть их. Рекомендую сделать специальный канал '
         f'для музыки и прописать там `.music`.\nЕсли тебе интересно поподробнее '
         f'узнать о других моих возможностях, напиши `.help`')
     embed.set_image(url='https://i.ibb.co/QmfMN1b/image.gif')
     embed.set_footer(text=f'версия {version}')
     await info.send(embed=embed)
     os.mkdir(f'{guild.id}')
     d = {
         'autoroles': {},
         'autoroles_post_id': None,
         'genders': [],
         'dj': None,
         'music_id': None,
         'channels': [],
         'current': None,
         'now': True,
         'notice': True,
         'count': 5
     }
     data_write(guild, d)
     with open(f"{guild.id}/history.json", "w") as f:
         json.dump([], f)
コード例 #3
0
ファイル: serv.py プロジェクト: sunic3/flex-bot
 async def notice_(self, ctx):
     channel_check(ctx)
     await ctx.message.delete()
     d = data_read(ctx.guild)
     d['notice'] = not d['notice']
     data_write(ctx.guild, d)
     await ctx.send(f'Настройка `участник покинул канал` изменена на  [ {int(d["notice"])} ]  :thumbsup:',
                    delete_after=20)
コード例 #4
0
ファイル: serv.py プロジェクト: sunic3/flex-bot
 async def count_(self, ctx, *, n: int):
     channel_check(ctx)
     await ctx.message.delete()
     d = data_read(ctx.guild)
     if n < 5 or n > 10:
         raise commands.errors.BadArgument
     d['count'] = n
     data_write(ctx.guild, d)
     await ctx.send(f'Настройка `количество записей` изменена на  [ {n} ]  :thumbsup:', delete_after=20)
コード例 #5
0
 async def notice_(self, ctx):
     d = data_read(ctx.guild)
     if ctx.message.author.id in d['notices']:
         d['notices'].remove(ctx.message.author.id)
     else:
         d['notices'].append(ctx.message.author.id)
     data_write(ctx.guild, d)
     await ctx.send(f'`{ctx.message.author.name}` всё :ok:',
                    delete_after=80)
コード例 #6
0
ファイル: serv.py プロジェクト: sunic3/flex-bot
 async def channels_(self, ctx, *chans: discord.TextChannel):
     await ctx.message.delete()
     if not chans:
         d = data_read(ctx.guild)
         d['channels'] = []
         data_write(ctx.guild, d)
         await ctx.send('Теперь можно писать команды в любом чате :hugging:', delete_after=20)
         return
     d = data_read(ctx.guild)
     d['channels'] = [chan.id for chan in chans]
     data_write(ctx.guild, d)
     await ctx.send(f'Эт{wordend(len(chans), "от", "и", "и")} {len(chans)} канал{wordend(len(chans), "", "а", "ов")}'
                    f' успешно установлен{wordend(len(chans), "", "ы", "ы")} как разрешённые :thumbsup::thumbsup:',
                    delete_after=40)
コード例 #7
0
ファイル: serv.py プロジェクト: sunic3/flex-bot
 async def set_genders(self, ctx, *roles: typing.Union[discord.Role, str]):
     s = ctx.message.author.guild
     if len(roles) == 0:
         r1 = await s.create_role(name='♂', colour=discord.Colour.blue(), mentionable=True)
         r2 = await s.create_role(name='♀', colour=discord.Colour(16711893), mentionable=True)
     elif len(roles) == 2:
         if isinstance(roles[0], discord.Role):
             r1 = roles[0]
             r2 = roles[1]
         else:
             r1 = await s.create_role(name=roles[0], colour=discord.Colour.blue(), mentionable=True)
             r2 = await s.create_role(name=roles[1], colour=discord.Colour(16711893), mentionable=True)
     else:
         raise errors.BadArgument
     d = data_read(ctx.guild)
     d['genders'] = [r1.id, r2.id]
     data_write(ctx.guild, d)
     await ctx.message.delete()
     await ctx.send(f'" роли[`{r1.name}` и `{r2.name}`] успешно установлены как гендерные :male_sign: :female_sign:',
                    delete_after=40)
コード例 #8
0
 async def set_genders(self, ctx, *roles: typing.Union[discord.Role, str]):
     s = ctx.message.author.guild
     if len(roles) == 0:
         r1 = await s.create_role(name='♂',
                                  colour=discord.Colour.blue(),
                                  mentionable=True)
         r2 = await s.create_role(name='♀',
                                  colour=discord.Colour(16711893),
                                  mentionable=True)
         d = data_read(ctx.guild)
         d['genders'] = [r1.id, r2.id]
         data_write(ctx.guild, d)
     elif len(roles) == 2:
         if isinstance(roles[0], discord.Role):
             d = data_read(ctx.guild)
             d['genders'] = [roles[0].id, roles[1].id]
             data_write(ctx.guild, d)
         else:
             r1 = await s.create_role(name=roles[0],
                                      colour=discord.Colour.blue(),
                                      mentionable=True)
             r2 = await s.create_role(name=roles[1],
                                      colour=discord.Colour(16711893),
                                      mentionable=True)
             d = data_read(ctx.guild)
             d['genders'] = [r1.id, r2.id]
             data_write(ctx.guild, d)
     else:
         raise errors.BadArgument
コード例 #9
0
    async def set_roles_(self, ctx, *role: typing.Union[discord.Role, str]):
        try:
            text, reacts = '', {}
            for i in range(len(role)):
                r = role[i]
                t = []
                if isinstance(r, discord.Role):
                    t.append(r)
                    if i < len(role) - 1 and isinstance(role[i + 1], str):
                        t.append(role[i + 1])
                        i += 1
                        if i < len(role) - 1 and isinstance(role[i + 1], str):
                            t.append(f' --- {role[i+1]}')
                            i += 1
                        else:
                            t.append("")
                    else:
                        print('h1')
                        raise commands.errors.BadArgument
                    text += f'{t[1]} : {t[0].mention}{t[2]}\n\n'
                    reacts[t[1]] = t[0].id

            embed = discord.Embed(title="Раздача ролей",
                                  description=text,
                                  colour=discord.Colour.green())
            embed.set_thumbnail(url=ctx.message.author.guild.owner.avatar_url)
            embed.set_footer(
                text='Нажмите на соответствующий Эмодзи, чтобы получить роль\n'
            )

            d = data_read(ctx.guild)
            if not d['autoroles_post_id']:
                sms = await ctx.send(embed=embed)
                await sms.pin()
                d['autoroles'] = reacts
                d['autoroles_post_id'] = sms.id
                data_write(ctx.guild, d)
                for e in reacts:
                    await sms.add_reaction(e)
                await ctx.message.delete()
            else:
                new_sms = await ctx.send(
                    f'Пост для выдачи авторолей уже сущесвует :pushpin:\nСоздать новый?'
                )
                await new_sms.add_reaction('🆕')
                await new_sms.add_reaction('🚫')

                def check(reaction, user):
                    return user == ctx.message.author

                try:
                    reaction, user = await self.client.wait_for('reaction_add',
                                                                check=check,
                                                                timeout=60)
                    if str(reaction.emoji) == '🆕':
                        if len(reacts) > 20:
                            await ctx.send(
                                'Не удалось создать пост, т.к. невозможно добавить более 20 реакций на '
                                'сообщение :no_entry:',
                                delete_after=40)
                            return
                        d = data_read(ctx.guild)
                        sms = await ctx.send(embed=embed)
                        await sms.pin()
                        d['autoroles'] = reacts
                        d['autoroles_post_id'] = sms.id
                        data_write(ctx.guild, d)
                        for e in reacts:
                            await sms.add_reaction(e)
                        await ctx.message.delete()
                    await new_sms.delete()
                except asyncio.TimeoutError:
                    await new_sms.delete()
        except IndexError:
            await ctx.send(
                "Слишком много ролей без эмоджи. Попробуй заполнить их своими смайлами."
            )
        except discord.HTTPException as e:
            if e.text == 'Unknown Emoji':
                await ctx.send(
                    "Дискорд не смог распознать некоторые Эмодзи :anguished:\nПопробуй ещё раз",
                    delete_after=30)
            else:
                pass
        except commands.errors.BadArgument:
            await ctx.send(
                "Данные введены неправильно, проверь ещё раз :writing_hand:",
                delete_after=20)
        except Exception:
            await exp(ctx)
        finally:
            try:
                await asyncio.sleep(10)
                await ctx.message.delete()
            except discord.HTTPException:
                pass
コード例 #10
0
ファイル: serv.py プロジェクト: sunic3/flex-bot
    async def set_roles_(self, ctx, *role: typing.Union[discord.Role, str]):
        if len(role) == 0:
            return await ctx.send(f'Ты забыл{postix(ctx)} указать роли')
        try:
            embed = discord.Embed(
                title="Раздача ролей",
                description='',
                colour=discord.Colour.green()
            )
            if isinstance(role[0], str):
                if role[0] != '-i':
                    embed.description = role[0]+'\n\n'
                    if len(role) > 1 and isinstance(role[1], str) and role[1] == '-i':
                        pass
                    else:
                        embed.set_thumbnail(url=ctx.guild.icon_url)
                else:
                    embed.set_thumbnail(url=ctx.guild.icon_url)
            embed.set_footer(text='Нажмите на соответствующий Эмодзи, чтобы получить роль\n')

            text, reacts = '', {}
            for i in range(len(role)):
                r = role[i]
                t = []
                if isinstance(r, discord.Role):
                    t.append(r)
                    if i < len(role)-1 and isinstance(role[i+1], str):
                        t.append(role[i+1])
                        i += 1
                        if i < len(role)-1 and isinstance(role[i+1], str):
                            t.append(f' --- {role[i+1]}')
                            i += 1
                        else:
                            t.append("")
                    else:
                        raise commands.errors.BadArgument
                    text += f'{t[1]} : {t[0].mention}{t[2]}\n\n'
                    reacts[t[1]] = t[0].id
            embed.description += text
            d = data_read(ctx.guild)
            if not d['autoroles_post_id']:
                sms = await ctx.send(embed=embed)
                await sms.pin()
                d['autoroles'] = reacts
                d['autoroles_post_id'] = f'{ctx.channel.id},{sms.id}'
                data_write(ctx.guild, d)
                for e in reacts:
                    await sms.add_reaction(e)
                await ctx.message.delete()
            else:
                new_sms = await ctx.send(f'Пост для выдачи авторолей уже сущесвует :pushpin:\nСоздать новый?')
                await new_sms.add_reaction('🆕')
                await new_sms.add_reaction('🚫')

                def check(reaction, user):
                    return user == ctx.message.author
                try:
                    reaction, user = await self.client.wait_for('reaction_add', check=check, timeout=60)
                    if str(reaction.emoji) == '🆕':
                        if len(reacts) > 20:
                            await ctx.send('Не удалось создать пост, т.к. невозможно добавить более 20 реакций на '
                                           'сообщение :no_entry:', delete_after=40)
                            return
                        try:
                            msg_d = await discord.utils.get(ctx.guild.text_channels,
                                                            id=int(d['autoroles_post_id'].split(',')[0]))\
                                .fetch_message(int(d['autoroles_post_id'].split(',')[1]))
                            await msg_d.delete()
                        except discord.HTTPException:
                            pass
                        except AttributeError:
                            pass
                        d = data_read(ctx.guild)
                        sms = await ctx.send(embed=embed)
                        await sms.pin()
                        d['autoroles'] = reacts
                        d['autoroles_post_id'] = f'{ctx.channel.id},{sms.id}'
                        data_write(ctx.guild, d)
                        for e in reacts:
                            await sms.add_reaction(e)
                        await ctx.message.delete()
                    await new_sms.delete()
                except asyncio.TimeoutError:
                    await new_sms.delete()
        except IndexError:
            await ctx.send("Аргументы переданы неверно :jack_o_lantern:", delete_after=40)
        except discord.HTTPException as e:
            if e.text == 'Unknown Emoji':
                await ctx.send("Дискорд не смог распознать некоторые Эмодзи :anguished:\nПопробуй ещё раз",
                               delete_after=30)
            else:
                pass
        except commands.errors.BadArgument:
            await ctx.send("Данные введены неправильно, проверь ещё раз :writing_hand:", delete_after=20)
        except Exception:
            await exp(ctx)
        finally:
            try:
                await asyncio.sleep(10)
                await ctx.message.delete()
            except discord.HTTPException:
                pass