discord bot only detects messages when it is mentioned - python-3.x

I made a discord selfbot that should detect every sent message and respond randomly to it. However, when I put it in a server with 450k people it only can detect those messages if they mention the account. This is the code
import os
import discord
import time
import random
import string
from discord.utils import get
from discord.ext import commands
TOKEN = "suwhgiowejvoifghoirwfofrgowegvofdgrovugdgovjfeogjrwo"
client=commands.Bot(command_prefix='', self_bot=True, fetch_offline_members=False)
#client.event
async def on_ready():
print('connected to Discord!')
#client.event
async def on_message(message):
print('message received')
time.sleep(60)
response=[
'hi',
'hello',
'interesting',
'no',
'bruh',
'.',
'oof',
'lol',
'lmao',
'yeah'
]
try:
await message.channel.send(random.choice(response))
print('message sent')
except:
print("message error")
pass
client.run(TOKEN, bot=False)
The issue is probably just that there are way too many people and it won't work. However, if you think that it may be something else please let me know.
(I know selfbots are against the ToS and that my account could get banned please don't get pissed at me)

It could be with the fetch_offline_members=False or the time.sleep(60), I can't think of sth else

Related

Send a screenshot to discord channels

I am writing a program that screenshots my computer screen and send it to my discord channel. This is done by a discord bot made by me. Below shows what I did:
First, define a function that does a screenshot:
import keyboard
import mouse
import os
def screenshot():
keyboard.press('win + shift + s')
time.sleep(1.5)
mouse.press('left')
mouse.drag(0, 0, 1600, 850, duration=0.2)
mouse.release('left')
filename = f"Screenshot_{time.strftime('%Y%m%d')}_{time.strftime('%I%M%S')}.png"
os.chdir('Path_of_screenshot_saves_here') # I have tested it, the path is correct
time.sleep(1)
with open(filename, 'r') as f:
return f
Then, the code of the discord bot:
import discord
import keyboard
import time
import os
import mouse
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'Logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$ss'): # sends a screenshot when it receives a message starts with '$ss'
await message.channel.send(screenshot())
client.run('my_bot_token_here')
The bot does send something to the channel. However, instead of sending out a png file, it sends something like this:
<io.TextIOWrapper name='Screenshot_20230219_030537.png' mode='r' encoding='cp1252'>
What have I done wrong? Are there any ways to solve this? Thanks for any help in advance.

Discord.py not responding to #client.event commands

I am not getting a "ping" response with this code. It was working before, but I am not sure what changed. There are no errors on my end, just no response.
Any feedback is appreciated.
import os
import random
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
PREFIX = os.getenv("PREFIX")
TOKEN = os.getenv("TOKEN")
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
#bot.event # ping-with-latency
async def on_message(message):
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')
#bot.event
async def on_ready(): # display if online/ready
print("Bot is ready and logged in as {0.user}!".format(bot))
# run bot on server
bot.run(TOKEN)
I have checked all permissions and privileged gateway intents. I know I could be using client.command, but that also doesnt work.
You're defining two different callbacks for these events - this is probably the problem. Just put the author check in the main on_message.
#bot.event
async def on_message(message):
if message.author == bot.user: # tells the bot not to respond to itself
return
if message.content.startswith(PREFIX + 'ping'):
await message.channel.send(f'pong! {bot.latency}ms')

How do i make a discord bot receive text after a command

I want to become a fake discord bot, so i can use: !!send or something like that.
I have the token ready and i tried some repl.it templates but i have no idea of what to do.
here is the code i tried:
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
os.environ["TOKEN"] = "no-token-for-you-to-see-here"
#^ basic imports for other features of discord.py and python ^
client = discord.Client()
client = commands.Bot(command_prefix = '!!') #put your own prefix here
#client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
#client.command(pass_context=True)
async def send(ctx,*,message):
await client.say(message)
client.run(os.getenv("TOKEN")) #get your bot token and create a key named `TOKEN` to the secrets panel then paste your bot token as the value.
#to keep your bot from shutting down use https://uptimerobot.com then create a https:// monitor and put the link to the website that appewars when you run this repl in the monitor and it will keep your bot alive by pinging the flask server
#enjoy!
It was online, but the command didn't work.
The command send should be
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
Also, you're defining two client(s). You need only one.
client = commands.Bot(command_prefix = '!!')
You're also importing some useless modules that you don't need right now.
Your final code should look like this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!!")
#client.event
async def on_ready():
print("The bot is online")
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
client.run("token-of-the-bot")
Please tell me if it works or not. Have a great day :)

discord.py send pm on member join

I'm trying to write a bot that sends a user a pm when he joins the server.
I searched and I found that to d this you need to have intents enabled, but when I enable them it gives me an error "RuntimeError: Event loop is closed". I can't figure out what exactly not working, I've seen somewhere that regenerate the bot token helps but it didn't help for me.
this is the code:
import discord
from discord.ext import commands
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member}"
await member.send(welcome_msg)
bot.run(TOKEN)
I see that you are trying to DM the user as soon as they join a server, you should did {member} and the argument "member" is just a guild version of The user, and to display the name with member.name there for it will show the Member's name on the message.
Here is your Fixed Code:
import discord
from discord.ext import commands, tasks # add tasks if you're going to do tasks.
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member.name}" # You don't need to define the message.
await member.send(welcome_msg) # You can do await member.send("message") instead of defining it.
bot.run(TOKEN)
Hope this helped. Have a nice day!

Discord.py Image Posting

I'm trying to make a bot that posts a random image (for this example lets say bread) from google images. Right now I'm stuck with trying to post the image to Discord.
Here is the code:
import discord
import io
import aiohttp
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('/bread'):
#await message.channel.send('bread!')
async with aiohttp.ClientSession() as session:
async with session.get("https://www.google.com/search?q=bread&tbm=isch") as resp:
if resp.status != 200:
return await message.channel.send('Could not download file...')
data = io.BytesIO(await resp.read())
await message.channel.send(file=discord.File(data, 'image.png'))
client.run('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
Whenever I run the /bread command, I run into the could not download file error.
I don't want to download the image, I just want it posted to discord. I tried selecting a specific image URL, it too did not work.
About picture:
You can go at igmur.com and create own link to picture. You just have to drag picture to the site.(this pictures works at discord)
And that's my script for posting URL by bot
import random
Import discord
import http.client
from discord.ext import commands
Import aiohttp
#bot.command()
async def /bread(ctx):
messages = ["url", "bread2url", "bread3url"]
await ctx.send(random.choice(messages))

Resources