Fsoky

Весь код с уроков по Discord BOT Python (+ несколько команд)

Aug 12th, 2020
3,276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.37 KB | None | 0 0
  1. import discord
  2. from random import randint, choice
  3. from discord.ext import commands
  4. import datetime, pyowm
  5. import speech_recognition as sr
  6. from discord.utils import get
  7. import youtube_dl
  8.  
  9. import os
  10. from time import sleep
  11. import requests
  12. from PIL import Image, ImageFont, ImageDraw
  13. import io
  14. import asyncio
  15.  
  16. """
  17. ЕСЛИ У ТЕБЯ ЧТО-ТО НЕ РАБОТАЕТ...
  18. УСТАНОВИ МОДУЛИ.. НЕ ЗНАЕШЬ КАК? ГУГЛИ
  19. """
  20.  
  21. PREFIX = '.'
  22. bad_words = [ 'кик', 'флуд', 'спам', 'бан' ]
  23.  
  24. client = commands.Bot( command_prefix = PREFIX )
  25. client.remove_command( 'help' )
  26.  
  27. @client.event
  28. async def on_ready():
  29.     print( 'client connected' )
  30.  
  31.     await client.change_presence( status = discord.Status.do_not_disturb, activity = discord.Game( '.help' ) )
  32.  
  33. @client.event
  34. async def on_command_error( ctx, error ):
  35.     print(error)
  36.    
  37. @client.event
  38. async def on_member_join( member ):
  39.     channel = client.get_channel( 668428362045456415 )
  40.  
  41.     role = discord.utils.get( member.guild.roles, id = 668111865527795722 )
  42.  
  43.     await member.add_roles( role )
  44.     await channel.send( embed = discord.Embed( description = f'Пользователь ``{ member.name }``, присоеденился к нам!',
  45.                          color = 0x3ec95d ) )
  46.  
  47. # Filter
  48. @client.event
  49. async def on_message( message ):
  50.     await client.process_commands( message )
  51.  
  52.     msg = message.content.lower()
  53.  
  54.     if msg in bad_words:
  55.         await message.delete()
  56.         await message.author.send( f'{ message.author.name }, не надо такое писать!' )
  57.  
  58.  
  59. @client.command()
  60. async def math( ctx, a : int, arg, b : int ):
  61.     if arg == '+':
  62.         await ctx.send( f'Result: { a + b }' )
  63.  
  64.     elif arg == '-':
  65.         await ctx.send( f'Result: { a - b }' )
  66.  
  67.     elif arg == '/':
  68.         await ctx.send( f'Result: { a / b }' )
  69.  
  70.  
  71. @client.command()
  72. async def ip_info( ctx, arg ):
  73.     response = requests.get( f'http://ipinfo.io/{ arg }/json' )
  74.  
  75.     user_ip = response.json()[ 'ip' ]
  76.     user_city = response.json()[ 'city' ]
  77.     user_region = response.json()[ 'region' ]
  78.     user_country = response.json()[ 'country' ]
  79.     user_location = response.json()[ 'loc' ]
  80.     user_org = response.json()[ 'org' ]
  81.     user_timezone = response.json()[ 'timezone' ]
  82.  
  83.     global all_info
  84.     all_info = f'\n<INFO>\nIP : { user_ip }\nCity : { user_city }\nRegion : { user_region }\nCountry : { user_country }\nLocation : { user_location }\nOrganization : { user_org }\nTime zone : { user_timezone }'
  85.  
  86.     await ctx.author.send( all_info )
  87.  
  88. @client.command()
  89. async def key( ctx ):
  90.     import uuid
  91.  
  92.     await ctx.send( f'Key : { uuid.uuid4() }' )
  93.  
  94. @client.command()
  95. async def w( ctx, *, arg ):
  96.     owm = pyowm.OWM( 'e4e1efbc1a7afebbbc33ed068b32512c' )
  97.     city = arg
  98.  
  99.     observation = owm.weather_at_place( city )
  100.     w = observation.get_weather()
  101.     temperature = w.get_temperature( 'celsius' )[ 'temp' ]
  102.  
  103.     await ctx.send( f'Температура в { city } : { temperature }' )
  104.  
  105. @client.command()
  106. async def phone_info( ctx, arg ):
  107.     response = requests.get( f'https://htmlweb.ru/geo/api.php?json&telcod={ arg }' )
  108.  
  109.     user_country = response.json()[ 'country' ][ 'english' ]
  110.     user_id = response.json()[ 'country' ][ 'id' ]
  111.     user_location = response.json()[ 'country' ][ 'location' ]
  112.     user_city = response.json()[ 'capital' ][ 'english' ]
  113.     user_width = response.json()[ 'capital' ][ 'latitude' ]
  114.     user_lenth = response.json()[ 'capital' ][ 'longitude' ]
  115.     user_post = response.json()[ 'capital' ][ 'post' ]
  116.     user_oper = response.json()[ '0' ][ 'oper' ]
  117.  
  118.     global all_info
  119.     all_info = f'<INFO>\nCountry : { user_country }\nID : { user_id }\nLocation : { user_location }\nCity : { user_city }\nLatitude : { user_width }\nLongitude : { user_lenth }\nIndex post : { user_post }\nOperator : { user_oper }'
  120.  
  121.     await ctx.author.send( all_info )
  122.  
  123. # Clear message
  124. @client.command()
  125. @commands.has_permissions( administrator = True )
  126.  
  127. async def clear( ctx, amount : int ):
  128.     await ctx.channel.purge( limit = amount )
  129.  
  130.     await ctx.send(embed = discord.Embed(description = f':white_check_mark: Удалено {amount} сообщений', color=0x0c0c0c))
  131.  
  132. # Kick
  133. @client.command()
  134. @commands.has_permissions( administrator = True )
  135.  
  136. async def kick( ctx, member: discord.Member, *, reason = None ):
  137.     await ctx.channel.purge( limit = 1 )
  138.     await member.kick( reason = reason )
  139.  
  140.     emb = discord.Embed( title = 'Информация об изгнании', description = f'{ member.name.title() }, был выгнан в связи нарушений правил',
  141.     color = 0xc25151 )
  142.  
  143.     emb.set_author( name = member, icon_url = member.avatar_url )
  144.     emb.set_footer( text = f'Был изганан администратором { ctx.message.author.name }', icon_url = ctx.author.avatar_url )
  145.  
  146.     await ctx.send( embed = emb )
  147.  
  148. # Ban
  149. @client.command()
  150. @commands.has_permissions( administrator = True )
  151.  
  152. async def ban( ctx, member: discord.Member, *, reason = None ):
  153.     await ctx.channel.purge( limit = 1 )
  154.     await member.ban( reason = reason )
  155.  
  156.     emb = discord.Embed( title = 'Информация о блокировке участника', description = f'{ member.name }, был заблокирован в связи нарушений правил',
  157.     color = 0xc25151 )
  158.  
  159.     emb.set_author( name = member.name, icon_url = member.avatar_url )
  160.     emb.add_field( name = f'ID: { member.id }', value = f'Блокированный участник : { member }' )
  161.     emb.set_footer( text = 'Был заблокирован администратором {}'.format( ctx.author.name ), icon_url = ctx.author.avatar_url )
  162.  
  163.     await ctx.send( embed = emb )
  164.  
  165. # Unba
  166.  
  167. # Command help
  168. @client.command()
  169. async def help( ctx ):
  170.     emb = discord.Embed(
  171.         title = 'Навигация по командам :clipboard:',
  172.         color = 0x7aa13d
  173.      )
  174.  
  175.     emb.add_field( name = '**Основные команды**', value = '''
  176.         .time - узнать текущее время :clock3:
  177.         .ip_info - узнать информацию о IP адресе :satellite:
  178.         .phone_info - узнать информацию о номере телефона :iphone:
  179.         .w - узнать температуру в городе
  180.         ''' )
  181.  
  182.     emb.add_field( name = '**Приколюшки**', value = '''
  183.         .hack - взлом сервера :tools:
  184.         .joke - шутка дня :face_with_raised_eyebrow:
  185.         .fsociety - сектретная разработка :gear:
  186.         ''' )
  187.  
  188.     await ctx.send( embed = emb )
  189.  
  190. @client.command()
  191.  
  192. async def time( ctx ):
  193.     emb = discord.Embed( title = 'ВРЕМЯ', description = 'Вы сможете узнать текущее время', colour = discord.Color.green(), url = 'https://www.timeserver.ru' )
  194.  
  195.     emb.set_author( name = client.user.name, icon_url = client.user.avatar_url )
  196.     emb.set_footer( text = 'Спасибо за использование нашего бота!' )
  197.     emb.set_thumbnail( url = 'https://sun9-35.userapi.com/c200724/v200724757/14f24/BL06miOGVd8.jpg' )
  198.  
  199.     now_date = datetime.datetime.now()
  200.  
  201.     emb.add_field( name = 'Time', value = 'Time : {}'.format( now_date ) )
  202.  
  203.     await ctx.author.send( embed = emb )
  204.  
  205.  
  206. @client.command()
  207. async def join(ctx):
  208.     global voice
  209.     channel = ctx.message.author.voice.channel
  210.     voice = get(client.voice_clients, guild=ctx.guild)
  211.     if voice and voice.is_connected():
  212.         await voice.move_to(channel)
  213.     else:
  214.         voice = await channel.connect()
  215.         engine = pyttsx3.init()
  216.         engine.say('Привет, человечушки. Как жизнь на земле!?')
  217.         engine.runAndWait()
  218.  
  219. @client.command()
  220. async def leave(ctx):
  221.     channel = ctx.message.author.voice.channel
  222.     voice = get(client.voice_clients, guild=ctx.guild)
  223.     if voice and voice.is_connected():
  224.         await voice.disconnect()
  225.     else:
  226.         voice = await channel.connect()
  227.  
  228. @client.command()
  229. async def play(ctx, url : str):
  230.     song_there = os.path.isfile('song.mp3')
  231.  
  232.     try:
  233.         if song_there:
  234.             os.remove('song.mp3')
  235.             print('[log] Старый файл удален')
  236.     except PermissionError:
  237.         print('[log] Не удалось удалить файл')
  238.  
  239.     await ctx.send('Пожалуйста ожидайте')
  240.  
  241.     voice = get(client.voice_clients, guild = ctx.guild)
  242.  
  243.     ydl_opts = {
  244.         'format' : 'bestaudio/best',
  245.         'postprocessors' : [{
  246.             'key' : 'FFmpegExtractAudio',
  247.             'preferredcodec' : 'mp3',
  248.             'preferredquality' : '192'
  249.         }],
  250.     }
  251.  
  252.     with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  253.         print('[log] Загружаю музыку...')
  254.         ydl.download([url])
  255.  
  256.     for file in os.listdir('./'):
  257.         if file.endswith('.mp3'):
  258.             name = file
  259.             print(f'[log] Переименовываю файл: {file}')
  260.             os.rename(file, 'song.mp3')
  261.  
  262.     voice.play(discord.FFmpegPCMAudio('song.mp3'), after = lambda e: print(f'[log] {name}, музыка закончила свое проигрывание'))
  263.     voice.source = discord.PCMVolumeTransformer(voice.source)
  264.     voice.source.volume = 0.07
  265.  
  266.     song_name = name.rsplit('-', 2)
  267.     await ctx.send(f'Сейчас проигрывает музыка: {song_name[0]}')
  268.  
  269. @client.command(aliases = ['я', 'карта']) # .я
  270. async def card_user(ctx):
  271.     await ctx.channel.purge(limit = 1)
  272.  
  273.     img = Image.new('RGBA', (400, 200), '#232529')
  274.     url = str(ctx.author.avatar_url)[:-10]
  275.  
  276.     response = requests.get(url, stream = True)
  277.     response = Image.open(io.BytesIO(response.content))
  278.     response = response.convert('RGBA')
  279.     response = response.resize((100, 100), Image.ANTIALIAS)
  280.  
  281.     img.paste(response, (15, 15, 115, 115))
  282.  
  283.     idraw = ImageDraw.Draw(img)
  284.     name = ctx.author.name # Fsoky
  285.     tag = ctx.author.discriminator # 9610
  286.  
  287.     headline = ImageFont.truetype('arial.ttf', size = 20)
  288.     undertext = ImageFont.truetype('arial.ttf', size = 12)
  289.  
  290.     idraw.text((145, 15), f'{name}#{tag}', font = headline) # Fsoky#9610
  291.     idraw.text((145, 50), f'ID: {ctx.author.id}', font = undertext)
  292.  
  293.     img.save('user_card.png')
  294.  
  295.     await ctx.send(file = discord.File(fp = 'user_card.png'))
  296.  
  297.  
  298. @client.command(aliases = ['mute'])
  299. async def __mute(ctx, member: discord.Member = None, amount_time = None, *, reason = None):
  300.     if member is None:
  301.         await ctx.send(embed = discord.Embed(
  302.             title = f'{ctx.author.mention}, **укажите пользователя**',
  303.             description = f'Пример: .mute **@user** time reason'
  304.         ))
  305.     elif amount_time is None:
  306.         await ctx.send(embed = discord.Embed(
  307.             title = f'{ctx.author.mention}, **укажите кол-во времени**',
  308.             description = f'Пример: .mute @user **time** reason'
  309.         ))
  310.     elif reason is None:
  311.         await ctx.send(embed = discord.Embed(
  312.             title = f'{ctx.author.mention}, **укажите причину**',
  313.             description = f'Пример: .mute @user time **reason**'
  314.         ))
  315.     else:
  316.         if 'm' in amount_time:
  317.             await ctx.send(embed = discord.Embed(
  318.                 description = f'''**[<:_off:714370680463949834>]** Вы были замучены на **{amount_time}**.
  319.                 **Выдал мут:** {ctx.author}
  320.                 ```css
  321. Причина: [{reason}]
  322.                 ```
  323.                 ''',
  324.                 color = 0x36393E,
  325.             ))
  326.  
  327.             mute_role = discord.utils.get(ctx.guild.roles, id = 714369082492846150)
  328.             await member.add_roles(mute_role)
  329.             await asyncio.sleep(int(amount_time[:-1]) * 60)
  330.             await member.remove_roles(mute_role)
  331.  
  332.             await ctx.send(embed = discord.Embed(
  333.                 description = f'''**[<:_on:714370680312954980>]** Время мута истекло, вы были размучены''',
  334.                 color = 0x2F3136
  335.             )) 
  336.         elif 'h' in amount_time:
  337.             await ctx.send(embed = discord.Embed(
  338.                 description = f'''**[<:_off:714370680463949834>]** Вы были замучены на **{amount_time}**.
  339.                 **Выдал мут:** {ctx.author}
  340.                 ```css
  341. Причина: [{reason}]
  342.                 ```
  343.                 ''',
  344.                 color = 0x36393E,
  345.             ))
  346.  
  347.             mute_role = discord.utils.get(ctx.guild.roles, id = 714369082492846150)
  348.             await member.add_roles(mute_role)
  349.             await asyncio.sleep(int(amount_time[:-1]) * 60 * 60)
  350.             await member.remove_roles(mute_role)
  351.  
  352.             await ctx.send(embed = discord.Embed(
  353.                 description = f'''**[<:_on:714370680312954980>]** Время мута истекло, вы были размучены''',
  354.                 color = 0x2F3136
  355.             )) 
  356.         elif 'd' in amount_time:
  357.             await ctx.send(embed = discord.Embed(
  358.                 description = f'''**[<:_off:714370680463949834>]** Вы были замучены на **{amount_time}**.
  359.                 **Выдал мут:** {ctx.author}
  360.                 ```css
  361. Причина: [{reason}]
  362.                 ```
  363.                 ''',
  364.                 color = 0x36393E,
  365.             ))
  366.  
  367.             mute_role = discord.utils.get(ctx.guild, id = 714369082492846150)
  368.             await member.add_roles(mute_role)
  369.             await asyncio.sleep(int(amount_time[:-1]) * 60 * 60 * 24)
  370.             await member.remove_roles(mute_role)
  371.  
  372.             await ctx.send(embed = discord.Embed(
  373.                 description = f'''**[<:_on:714370680312954980>]** Время мута истекло, вы были размучены''',
  374.                 color = 0x2F3136
  375.             )) 
  376.         else:
  377.             await ctx.send(embed = discord.Embed(
  378.                 description = f'''**[<:_off:714370680463949834>]** Вы были замучены на **{amount_time}s**.
  379.                 **Выдал мут:** {ctx.author}
  380.                 ```css
  381. Причина: [{reason}]
  382.                 ```
  383.                 ''',
  384.                 color = 0x36393E,
  385.             ))
  386.  
  387.             mute_role = discord.utils.get(ctx.guild.roles, id = 714369082492846150)
  388.             await member.add_roles(mute_role)
  389.             await asyncio.sleep(int(amount_time))
  390.             await member.remove_roles(mute_role)
  391.  
  392.             await ctx.send(embed = discord.Embed(
  393.                 description = f'''**[<:_on:714370680312954980>]** Время мута истекло, вы были размучены''',
  394.                 color = 0x2F3136
  395.             )) 
  396.  
  397.  
  398. # Get token
  399. token = open('token.txt', 'r').readline()
  400. client.run( token )
Add Comment
Please, Sign In to add comment