I want to make it so that this discord bot can ping,portscan and whois Servers and IPs.All of the commands work perfectly fine but when I try to use pythonping i get a error which i can't see.i get this message in discord, <coroutine object Command.call at 0x04E55368> and this error in the Visual Studio Code terminal i get this error, C:\Users\swevl\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py:85: RuntimeWarning: coroutine 'Command.__call__' was never awaited ret = await coro(*args, **kwargs) RuntimeWarning: Enable tracemalloc to get the object allocation traceback.
Here is my code:
from discord.ext import commands
import json
import os
import random
import string
import time
import colorama
from colorama import Fore, Back, Style
import string
from os import system, name
import aiohttp
from pythonping import ping
import requests
# # # # # # # # # # Bot Config and Token # # # # # # # # # #
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
clear()
os.system("cls && title Gen Bot")
token = "Censored Bot Token"
client = commands.Bot(command_prefix='a!', case_insensitive=True)
client.remove_command('help')
print(f" {Fore.RED}╔═╗╦ ╔═╗╦ ╦╔═╗ ╔╗ ╔═╗╔╦╗")
print(f" {Fore.RED}╠═╣║ ╠═╝╠═╣╠═╣ ╠╩╗║ ║ ║ ")
print(f" {Fore.RED}╩ ╩╩═╝╩ ╩ ╩╩ ╩ ╚═╝╚═╝ ╩ ")
print(f"{Fore.YELLOW}I-----------------------------------------------------I")
#client.event
async def on_ready():
# login of client
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='a!help'))
print(f"{Fore.RED}[{Fore.YELLOW}STATUS{Fore.RED}] The bot just went online!".format(client))
#####Utiity Commands#####
#client.command()
async def clear(ctx, amount=100):
await ctx.channel.purge(limit=amount)
await ctx.send("Messages have been removed!", delete_after=4)
print (f'{Fore.RED}[{Fore.YELLOW}LOGS{Fore.RED}] {ctx.author} cleared {amount} messages')
#########################################################################################################################################
#client.command(name='whois')
async def whois(ctx, arg1):
if arg1 == "":
await ctx.send("Invalid IP!")
else:
async with aiohttp.ClientSession() as session:
async with session.get(f"http://ip-api.com/json/{arg1}?fields=66846719") as r:
js = await r.json()
myip = ('')
if myip == (js["query"]):
await ctx.send('Invalid Ip!')
else:
cont = (js["continent"])
country = (js["country"])
region = (js["regionName"])
city = (js["city"])
zipcode = (js["zip"])
iso = (js["isp"])
org = (js["org"])
reverse = (js["reverse"])
mobile = (js["mobile"])
proxy = (js["proxy"])
hosting = (js["hosting"])
embed1 = discord.Embed(title=(js["query"]), color = discord.Color.red())
embed1.add_field(name="info", value=(f"{ctx.author.mention}\n"
f"Continent: {cont} \n"
f"country: {country} \n"
f"Region: {region}\n"
f"City: {city} \n"
f"Zip: {zipcode} \n"
f"ISP: {iso} \n"
f"Org: {org} \n"
f"Reverse: {reverse} \n"
f"Mobile: {mobile} \n"
f"Proxy: {proxy} \n"
f"Hosting: {hosting}"), inline=False)
await ctx.send(embed=embed1)
print (f'{Fore.RED}[{Fore.YELLOW}LOGS{Fore.RED}] {ctx.author} used the whois comand on {arg1}')
#client.command()
async def portscan(ctx, arg1):
if arg1 == '':
await ctx.send("Invalid IP!")
else:
print (f'{Fore.RED}[{Fore.YELLOW}LOGS{Fore.RED}] {ctx.author} portscanned {arg1}')
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.hackertarget.com/nmap/?q={arg1}") as r:
if r.status == 200:
text = await r.text()
embed1 = discord.Embed(title=(f'Results from {arg1}'), description=(text), color = discord.Color.red())
await ctx.send(embed=embed1)
else:
await ctx.send("API is offline, try again later...")
#client.command()
async def ping(ctx, arg1):
if arg1 == '':
await ctx.send("Invalid IP!")
else:
await ctx.send(ping(arg1))
client.run(token)```
I can walk you through the error from your code:
#client.command()
async def ping(ctx, arg1):
if arg1 == '':
await ctx.send("Invalid IP!")
else:
await ctx.send(ping(arg1))
When you hit the else statement, you call the ping function again. You never awaited the ping function (it is a coro), which is why the error is being raised. From what you provided here, it seems this command would do nothing but eventually crash your discord bot. It would keep calling itself over and over again (infinite recursion).
What I think you're trying to do is have a command that pings an ip and returns a response. You need to use a different function to ping, you can't call the same one over and over again.
async def ping_ip(ip) -> str: # The function returns a string
... # Do pinging here and return a str
#client.command()
async def ping(ctx, ip: str):
data = await ping_ip(ip)
return await ctx.send(data)
i use this code to find the bot ping
#client.command()
#commands.guild_only()
async def ping(ctx):
embed = discord.Embed(title="Bot ping",
description=f"{round(client.latency * 1000)}ms",
color=discord.Colour.purple())
await ctx.send(embed=embed)
Related
this is the code. if you want any other info i can provide you with it, but as for right now this is the only place that i had hopes on. im literally stuck.
import os, json
from dotenv import load_dotenv, find_dotenv
import discord
from discord.ext import commands, tasks
import logging
import binance
from discord import Member
from discord.ext.commands import has_permissions, MissingPermissions
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename = 'discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(name)s:&(message)s'))
logger.addHandler(handler)
load_dotenv(find_dotenv())
token = os.getenv("DISCORD_TOKEN")
channel_id = os.getenv('CHANNEL_ID')
binance_api_key = os.getenv('BINANCE_API_KEY')
binance_api_secret = os.getenv('BINANCE_API_SECRET')
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents, command_prefix='..')
binanceClient = Client(binance_api_key, binance_api_secret)
FAV_LIST = {}
with open('FAV_LIST.json') as f:
FAV_LIST = json.load(f)
def get_future_position(symbol):
position = None
positions = list(filter(lambda f:(f['symbol']==symbol), binanceClient.futures_account()['positions']))
if positions:
position = positions[0]
return position
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello!')
#commands.command()
async def add_fav(ctx, account, symbol):
FUT_SYMBOLS = [sym['symbol'] for sym in binanceClient.futures_exchange_info()['symbols']]
SPOT_SYMBOLS = [sym['symbol'] for sym in binanceClient.get_all_tickers()]
if account.upper() == "FUT":
if symbol in FUT_SYMBOLS:
FAV_LIST['FUTURES'][symbol] = {}
else:
await ctx.send("Provided SYMBOL or CRYPTO is not available in Futures")
elif account.upper() == "SPOT":
if symbol in SPOT_SYMBOLS:
FAV_LIST['SPOT'][symbol] = {}
else:
await ctx.send("Provided SYMBOL or CRYPTO is not available in SPOT")
else:
await ctx.send('Provided Account Type is not valid. Please use FUT for Futures and SPOT for spot')
with open('FAV_LIST.json','w') as f:
json.dump(FAV_LIST, f)
#commands.command()
async def favs(ctx):
message = "FUTURES FAVOURITE LIST\n"
for i, symbol in enumerate(FAV_LIST['FUTURES'].keys()):
message += str(i+1) + ". " + symbol + "--> Last Price: "+ binanceClient.get_ticker(symbol=symbol)['lastPrice']+"\n"
message += "\n\nSPOT FAVOURITE LIST"
for i, symbol in enumerate(FAV_LIST['SPOT'].keys()):
message += str(i+1) + ". " + symbol + "--> Last Price: "+ binanceClient.get_ticker(symbol=symbol)['lastPrice']+ "\n"
await ctx.send(message)
#commands.command()
async def fubln(ctx):
balance_list = binanceClient.futures_account_balance()
message = "-"*35 + "\n"
message += "-"*3 + "ACCOUNT BALANCE" + "-"*3 + "\n"
message += "-"*35 +"\n"
for balance in balance_list:
message += balance['asset']+" : "+balance['balance']+"\n"
message += "-"*35
await ctx.send(message)
#tasks.loop(seconds=60)
async def futures_position_alerts():
futures_info = binanceClient.futures_account()
positions_info = binanceClient.futures_position_information()
positions = futures_info['positions']
message_channel = await client.fetch_channel(channel_id)
print(f"Got channel {message_channel} for {channel_id}")
if float(futures_info['totalMaintMargin'])/float(futures_info['totalMarginBalance']) > 40.0:
await message_channel.send("Your positions' Margin Ratio is greater than 40%. Please consider taking a look at it.")
for position in positions:
symbol = position['symbol']
alert = False
message = "------"+symbol+" POSITION ALERT!------\n"
position_info = list(filter(lambda f:(f['symbol']==symbol),positions_info))[0]
if float(position_info['positionAmt']) != 0.0:
if float(position['unrealizedProfit']) < -1.0 :
message += "Unrealized Profit is going down! LOSS : "+ str(position['unrealizedProfit']) +"\n"
alert = True
if (float(position_info['markPrice'])-float(position_info['liquidationPrice']))/(float(position_info['entryPrice'])-float(position_info['liquidationPrice'])) <= 0.4:
message += "Mark price is moving closer to Liquidation Price. Your position may be liquidated soon.\n Mark Price:"+ str(position_info['markPrice']) +"\n Liquidation Price:"+str(position_info['liquidationPrice'])+"\n"
alert = True
if alert:
await message_channel.send(message)
#futures_position_alerts.before_loop
async def before():
await client.wait_until_ready()
print("Finished waiting")
futures_position_alerts.start()
##tasks.loop(seconds=60)
#async def favs_info():
# message = "INFO of Favourite Crytos\n\n"
# message += "FUTURES\n"
# for i, symbol in enumerate(FAV_LIST['FUTURES'].keys()):
# position = get_future_position(symbol)
# message += str(i)+". "+position['symbol']+" --> unrealizedProfit : "+position['unrealizedProfit']
# message_channel = await client.fetch_channel(channel_id)
# print(f"Got channel {message_channel} for {channel_id}")
# await message_channel.send(message)
##favs_info.before_loop
#async def before():
# await client.wait_until_ready()
# print("Finished waiting")
#favs_info.start()
# MODERATION COMMANDS #
#commands.command()
#has_permissions(kick_members=True, administrator=True)
async def kick(ctx, member:discord.Member,*,reason=None):
guild = ctx.guild
memberKick = discord.Embed(title='Kicked', description = f'You have been kicked from {guild.name} for {reason}')
await member.kick(reason=reason)
await ctx.send(f'User {member} has been kicked.')
#commands.command()
#has_permissions(ban_members=True, administrator=True)
async def ban(ctx, member:discord.Member,*,reason=None,):
guild = ctx.guild
memberBan = discord.Embed(title = 'Banned', description=f'You were banned from {guild.name} for {reason}')
await member.ban(reason=reason)
await ctx.send(f'User {member} has been banned.')
await member.send(embed=memberBan)
#commands.command()
#has_permissions(ban_members=True, administrator=True)
async def unban(self, ctx, *, member:discord.Member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'{user.name}#{user.discriminator} has been unbanned.')
return
#commands.command(pass_context=True)
#has_permissions(manage_messages=True)
async def mute(ctx,member:discord.Member, reason = None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name='Muted')
memberMute = discord.Embed(title = 'Muted', description=f'You have been muted from {guild.name} for {reason}')
if mutedRole not in guild.roles:
perms = discord.Permissions(send_messages=False, speak=False)
await guild.create_role(name='Muted', permissions=perms)
await member.add_roles(mutedRole)
await ctx.send('Succesfuly created the [Muted] role and properly assigned it to the user.')
await ctx.add_role(member, mutedRole)
embed=discord.Embed(title='User muted!', description=f'**{0}** was muted by **{1}**!'.format(member, ctx.message.author, color=0xff00f6))
#commands.command(pass_context=True)
#has_permissions(manage_messages=True)
async def unmute(ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name = 'Muted')
memberUnmute = discord.Embed(title = 'Unmuted', description = f'You were unmuted from {guild.name} for {reason}')
await member.remove_roles(mutedRole)
await ctx.send(f'Unmuted {member.mention} for {reason}')
await member.send(embed=memberUnmute)
client.run(token)
#TRACEBACK#
Traceback (most recent call last):
File "c:\Users\arlit\Desktop\iceC-main\main.py", line 122, in <module>
futures_position_alerts.start()
File "C:\Users\arlit\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 398, in start
self._task = asyncio.create_task(self._loop(*args, **kwargs))
File "C:\Users\arlit\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 336, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
well i tried closing the loop but i didnt get it to work exactly how i wanted it to.
Edit: this is the whole code and the traceback below it. since it was too short. now ill have to add some random text since stack doesnt let me post too much code without adding some words.
You're calling futures_position_alerts.start() at the top level of your file. As the error message is telling you, you have to call it in an async context. There's an official example that you could look at.
My bot is not responding to commands, and there are no errors in the console. This is my code:
import discord
from discord.ui import Button, View
from discord.ext import commands
import database
from dotenv import load_dotenv
import asyncio
import os
load_dotenv('tokens.env')
TOKEN = os.getenv("DISCORD_TOKEN")
intents = discord.Intents().all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='?', intents=intents)
adventure_slots = [True, True, True]
adventurers = {}
#bot.command(aliases=["c"])
async def characters(ctx):
print(ctx)
username = ctx.author.display_name
page = 1
if len(ctx.content.split()) > 1:
page = int(ctx.content.split()[1])
offset = (page - 1) * 10
characters = database.get_characters(offset)
embed = discord.Embed(title="Character List", color=0x0eebeb)
character_list = ""
total_characters = 0
for character in characters:
character_list += "• " f"{character[1]} | {character[3]}\n"
total_characters+=1
embed.add_field(name=f"{username}" " has a total of " f"{total_characters}" " characters:", value=character_list, inline=False)
bot.process_commands(ctx)
footer_text = ""
if page > 1:
footer_text += "<< Prev"
if len(characters) == 10:
footer_text += " | Next >>"
embed.set_footer(text=footer_text)
# Send the character list message
await ctx.channel.send(embed=embed)
print (ctx)
#bot.command(aliases=["a"])
async def adventure(ctx):
print(ctx)
if all(not slot for slot in adventure_slots):
await ctx.send("All adventure slots are currently full. Please try again later.")
return
message = await ctx.send("Please pick the character you would like to send by typing `r!'character_name'`")
def check(m):
return m.author == ctx.author and m.content.startswith("r!'") and len(m.content.split()) == 2
try:
character_message = await bot.wait_for("message", check=check, timeout=60.0)
except asyncio.TimeoutError:
await ctx.send("Timed out waiting for character name. Please try the `r!adventure` command again.")
return
character_name = character_message.content.split()[1]
character = database.get_character(character_name)
if not character:
await ctx.send(f"Character `{character_name}` not found.")
return
for i, slot in enumerate(adventure_slots):
if not slot:
adventure_slots[i] = True
break
else:
return
await ctx.send(f"{character_name} has been sent on an adventure! They will return in 3 hours.")
await asyncio.sleep(3 * 3600) # 3 hours in seconds
await ctx.author.send(f"{character}'s adventure is complete! You can collect your loot now.")
bot.process_commands(ctx)
client.run(TOKEN)
I tried changing the commands to an on-message method and I tried removing the prefix entirely and using the prefix on the on_message method and more, I tried reading on forums and on Stack Overflow, but nothing seems to work...
You made both a Client and a Bot. The Bot is the one which has commands, but you're running the Client.
TOKEN = os.getenv("DISCORD_TOKEN")
intents = discord.Intents().all()
client = discord.Client(intents=intents) # Not your Bot instance
bot = commands.Bot(command_prefix='?', intents=intents) # Your Bot instance
...
client.run(TOKEN) # Not your Bot instance
Get rid of your Client & run the Bot instead. There's never a reason to have both a Client and a Bot.
So I'm trying to make a music bot which just joins,plays,stops and resume music. However my bot can join and leave a voice channel fine, however when i do my /play command it get stuck on [youtube] oCveByMXd_0: Downloading webpage (this is output in vscode) and then does nothing after. I put some print statement (which you can see in the code below and it prints 1 and 2 but NOT 3). Anyone had this issue?
MUSIC BOT FILE
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def join(self, ctx):
if(ctx.author.voice is None):
await ctx.reply("*You're not in a voice channel.*")
voiceChannel = ctx.author.voice.channel
if(ctx.voice_client is None): # if bot is not in voice channel
await voiceChannel.connect()
else: # bot is in voice channel move it to new one
await ctx.voice_client.move_to(voiceChannel)
#commands.command()
async def leave(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self,ctx, url:str = None):
if(url == None):
await ctx.reply("*Check your arguments!*\n```/play VIDEO_URL```")
else:
ctx.voice_client.stop() # stop current song
# FFMPEG handle streaming in discord, and has some standard options we need to include
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YTDL_OPTIONS = {"format":"bestaudio"}
vc = ctx.voice_client
# Create stream to play audio and then stream directly into vc
with youtube_dl.YoutubeDL(YTDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
print("1")
url2 = info["formats"][0]["url"]
print("2")
source = await discord.FFmpegOpusAudio.from_probe(url2,FFMPEG_OPTIONS)
print("3")
vc.play(source) # play the audio
await ctx.send(f"*Playing {info['title']} -* 🎵")
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.reply("*Paused -* ⏸️")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.reply("*Resuming -* ▶️")
def setup(bot):
bot.add_cog(music(bot))
MAIN FILE
from discord.ext import commands
from dotenv import load_dotenv
from lxml import html
import youtube_dl
import requests
import random
import discord
import requests
import os
import music
# Load .env file
load_dotenv()
COGS = [music]
PREFIX = "/"
bot = commands.Bot(command_prefix=PREFIX, intents=discord.Intents.all())
for x in range(len(COGS)):
COGS[x].setup(bot)
# EVENTS #
#bot.event
async def on_ready():
await bot.get_channel(888736019590053898).send(f"We back online! All thanks to *sploosh* :D")
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
replies = ["Err is that even a command?", "Can you type bro?", "Yeah... thats not a command buddy.", "Sorry forgot you can't spell"]
await ctx.send(random.choice(replies))
#bot.event
async def on_message(message):
if str(message.channel) == "images-videos" and message.content != "":
await message.delete()
await bot.process_commands(message)
# COMMANDS #
#bot.command()
async def hello(ctx):
# Get a random fact
url = 'http://randomfactgenerator.net/'
page = requests.get(url)
tree = html.fromstring(page.content)
hr = str(tree.xpath('/html/body/div/div[4]/div[2]/text()'))
await ctx.reply("**Hello Bozo!**\n" + "*Random Fact : *" + hr[:-9]+"]")
#bot.command()
async def randomNum(ctx, start:int = None, end:int = None):
if(start == None or end == None):
await ctx.reply("*Check your arguments!*\n```/randomNum START_NUMBER END_NUMBER```")
else:
randNum = random.randint(start, end)
await ctx.reply(f"*{randNum}*")
#bot.command()
#commands.is_owner()
async def kick(ctx, member:discord.Member = None, *, reason="You smell bozo."):
if(member == None):
await ctx.reply("*Check your arguments!*\n```/kick #MEMBER REASON(optional)```")
elif ctx.author.id in (member.id, bot.user.id):
await ctx.reply("*You cant kick yourself/me you silly.*")
else:
await member.kick(reason=reason)
#bot.command()
#commands.is_owner()
async def ban(ctx, member:discord.Member = None, *, reason="Bye Bye! :D."):
if(member == None):
await ctx.reply("*Check your arguments!*\n```/kick #MEMBER REASON(optional)```")
elif ctx.author.id in (member.id, bot.user.id):
await ctx.reply("*You cant ban yourself/me you silly.*")
else:
await member.ban(reason=reason)
#bot.command()
#commands.is_owner()
async def close_bot(ctx):
replies = ["Well bye!", "Guess I go now?", "Please let me stay..."]
await ctx.send(random.choice(replies))
await bot.close()
if __name__ == "__main__":
bot.run(os.getenv("BOT_TOKEN"))
This is how my play music command is setup, and i know for sure it works and it seems like it should work for you too.
#commands.command()
async def play(self, ctx, *, song=None):
commandd = "play"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
this is some other things that you might need
import discord
from discord.ext import commands
from random import choice
import string
from discord.ext.commands.cooldowns import BucketType
import asyncio
import youtube_dl
import pafy
import datetime
from discord_slash import cog_ext, SlashContext
x = datetime.datetime.now()
from ult import *
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
I'm currently learning python (slowly) and have started writing a discord bot. However, when i call a #client.command function nothing happens in discord. For example .ping should reply with "pong!" but nothing happens and I do not get an error.
My code is below
import discord
from discord.ext import commands
import asyncio
import time
import discord.client
client = commands.Bot(command_prefix=".")
messages = joined = 0
bad_words = ["example"]
channel = ["general"]
#client.command()
async def kick(ctx, userName: discord.Member):
await client.kick(userName)
#client.event(message)
async def on_ready():
id = client.get_guild(705455096749752323)
print("hello")
async def update_stats():
await client.wait_until_ready()
global messages, joined
while not client.is_closed():
try:
with open("stats.txt", "a") as f:
f.write(f"""Messages: {messages}, Members Joined {joined}, time: {time.time()}\n""")
messages = 0
joined = 0
await asyncio.sleep(5)
except Exception as e:
print(e)
#client.event
async def on_member_update(before, after):
n = after.nick
if n:
if n.lower().count("Crysis Wolfie") > 0:
last = before.nick
if last:
await after.edit(nick=last)
else:
await after.edit(nick="NO STOP THAT!")
#client.event
async def on_member_update(before, after):
n = after.game
if n:
if n.lower.count(f"""{before.n}""") > 0:
discord.message.channel.send()
#client.event
async def on_member_join(member):
global joined
joined += 1
for channel in member.server.channels:
if str(channel) == "general":
await discord.message.channel_send(f"""Welcome to the server {member.mention}""")
#client.event
async def on_message(message, yes=None):
# chat commands
id = client.get_guild(705455096749752323)
channels = ["general", "apply"]
global messages
messages = + 1
if str(message.channel) in channels:
if message.content.find("!hello") != -1:
await message.channel.send(f"""What's cooking {message.author.mention} looking good today :wink:""")
elif message.content == "!users":
await message.channel.send(f"""Number of members {id.member_count}""")
if message.content.find("NHS") != -1:
await message.channel.send("https://tenor.com/view/goodjob-clap-nicework-great-gif-7248435")
if message.content.find("wolfie") != -1:
await message.channel.purge(limit=1)
await message.channel.send("https://tenor.com/view/facepalm-really-stressed-mad-angry-gif-16109475")
if message.content.find("crysis") != -1:
await message.channel.purge(limit=1)
await message.channel.send("https://tenor.com/view/facepalm-really-stressed-mad-angry-gif-16109475")
if message.content.find("!apply") != -1:
await message.channel.send(f"""TESTING""")
for word in bad_words:
if message.content.count(word) > 0:
await message.channel.purge(limit=1)
await message.channel.send(f"""User {message.author.mention} watch your language!""")
try:
with open("badwordlog.txt", "a") as n:
n.write(f"""member: {message.author}, said {message.content}, at {time.time()}\n""")
print(f"""member: {message.author}, said {message.content}""");
except Exception as e:
print(e)
await client.process_commands(message)
#client.event
async def on_member_update(before, after): # needs fixing
n = before.status
if n != before:
await discord.message.channel.send(f"""have fun on {after} """)
#client.command()
async def create_invite(self, ctx): # needs fixing
self = bot
"""Create invite"""
link = await ctx.channel.create_invite(max_age=300)
await ctx.send("Here is an instant invite to your server: " + link)
#client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
#client.command()
async def ping(ctx):
await ctx.send('pong!')
clint.run('my token is here but I have removed')
#client.event functions run fine and work great! But client.command does nothing :(.
thanks
I am making sort of a "hack" for dank memer. I have made my own bot. My goal with the bot was to get it to keep saying "pls search" about every 5 seconds. Eventually, I would make a command that says "pls give 100" to get the coins. Instead of showing up in discord, it showed up in my app.
#client.command()
async def go(ctx):
def printit():
threading.Timer(5.0, printit).start()
await ctx.send("pls search")
printit()
This will continuously send messages, but you will get rate-limited. This works by scheduling a task in the event loop that sends messages, then canceling it.
import asyncio
#bot.command()
async def comm(ctx):
async def f():
while True:
# await asyncio.sleep(.5) # Control message speed
await ctx.send('Test')
await ctx.send("Start")
task = asyncio.create_task(f())
await asyncio.sleep(5)
await ctx.send("End")
task.cancel()
You can do this:
import time
#bot.command()
async def start(ctx, number_of_times=5):
for i in range(number_of_times):
await ctx.send('pls search')
time.sleep(5)
# type in the user
await ctx.send('pls give <user> 100')
import discord, os, asyncio
from discord.ext import commands
from colorama import Fore, Style
token = "Token Here"
#Bot prefix, like ?help
prefix = ["|", "!", "/"]
def endSong(guild, path):
os.remove(path)
#Clear Command
def Clear():
os.system('clear')
#Colors
def RandomColor():
randcolor = discord.Color(random.randint(0x000000, 0xFFFFFF))
return randcolor
def RandString():
return "".join(
random.choice(string.ascii_letters + string.digits)
for i in range(random.randint(14, 32)))
#Prefix
client = discord.Client()
client = commands.Bot(command_prefix=prefix, self_bot=True)
#Dep
#client.command(name='dankmemer', aliases=['dank', 'dmc'])
async def dankmemer(ctx):
await ctx.message.delete()
count = 0
while True:
try:
count += 1
await ctx.send('pls beg')
print(
f'{Fore.BLUE}[AUTO-MEME] {Fore.GREEN}Meme number: {count} sent'
+ Fore.RESET)
await asyncio.sleep(26)
except Exception as e:
print(f"{Fore.RED}[ERROR]: {Fore.YELLOW}{e}" + Fore.RESET)
#Farm
#client.command(name='dank-farm', aliases=['dankfarm', "dm"])
async def _fish_dank(ctx): # b'\xfc'
await ctx.message.delete()
count = 0
while True:
try:
count += 1
await ctx.send('pls fish')
await ctx.send('pls hunt')
await ctx.send('pls dig')
print(
f'{Fore.BLUE}[AUTO-FARM] {Fore.GREEN}Farm number: {count} sent'
+ Fore.RESET)
await asyncio.sleep(26)
except Exception as e:
print(f"{Fore.RED}[ERROR]: {Fore.YELLOW}{e}" + Fore.RESET)
#onReady
#client.event
async def on_ready():
print(f"You are Online :)")
client.run(token, bot=False)