Sending messages in discord.py #tasks.loop() - python

Goal:
I am simply trying to send a message to a discord channel from a #tasks.loop() without the need for a discord message variable from #client.event async def on_message. The discord bot is kept running in repl.it using uptime robot.
Method / Background:
A simple while True loop in will not work for the larger project I will be applying this principle to, as detailed by Karen's answer here. I am now using #tasks.loop() which Lovesh has quickly detailed here: (see Lovesh's work).
Problem:
I still get an error for using the most common method to send a message in discord using discord.py. The error has to have something to do with the await channel.send( ) method. Neither of the messages get sent in discord. Here is the error message.
Code:
from discord.ext import tasks, commands
import os
from keep_alive import keep_alive
import time
token = os.environ['goofyToken']
# Set Up Discord Client & Ready Function
client = discord.Client()
channel = client.get_channel(CHANNEL-ID)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#tasks.loop(count=1)
async def myloop(word):
await channel.send(word)
#client.event
async def on_message(message):
msg = message.content
if msg.startswith('!'):
message_to_send = 'Hello World!'
await channel.send(message_to_send)
myloop.start(message_to_send)
keep_alive()
client.run(token)
Attempted Solutions:
A message can be sent from the on_message event using the syntax await message.channel.send('Hello World!). However, I just can't use this. The code is kept running online by uptimerobot, a free website which pings the repository on repl.it. When the robot pings the repository, the message variable is lost, so the loop would stop scanning my data in the larger project I am working on which is giving me this issue.

When using any client.get_* method the bot will try to grab the object from the cache, the channel global variable is defined before the bot actually runs (so the cache is empty). You should get the channel inside the loop function:
#tasks.loop(count=1)
async def myloop(word):
channel = client.get_channel(CHANNEL_ID)
await channel.send(word)

Related

How to send message to a specific discord channel

I am trying to send a message to a specific channel and I can run the code below just nothing show up on the channel and I have no idea why... I put the channel Id in the get_channel input, just putting a random number here.
import discord
client = discord.Client()
async def send_msg(msg):
channel = client.get_channel(123456456788)
await channel.send('hello')
Is the function even called somewhere? Otherwise there could also be an issue with the discord permissions or the Intents.
This is one of many ways to call the function and post 'hello' in some specific channel. No msg parameter is required.
#client.event
async def on_ready():
await send_msg()
async def send_msg():
channel = client.get_channel(123456456788)
await channel.send('hello')

Discord bot only working in pm, how can i fix this?

This is the code, it only answers me in private messages but not in any group chat.
import discord
import random
import time
import asyncio
token = "number that im not gonna show"
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print(f"Bot logged on as {client.user}")
#client.event
async def on_message(msg):
if msg.author == client.user:
return
if msg.content.lower().startswith("?hi"):
await msg.channel.send(f"Comrade {msg.author.display_name}, will you assist me in seizing the means of production?")
client.run(token)
You don't have the message_content intent, so you can't read messages except
DM's
Messages your bot is #mentioned in
If you'd like to read messages, enable this intent both in code and on the developer portal.
Docs: https://discordpy.readthedocs.io/en/stable/intents.html
PS. instead of manually trying to parse messages & prefixes, consider looking into the built-in ext.commands framework that does this all for you: https://discordpy.readthedocs.io/en/stable/ext/commands/index.html

On member join event message doesn't work - discord.py

I'm very new to discord.py, I want to learn python and make a simple bot for my server.
I want make a bot that sends a message when someone joins server. But the bot won't send any message. I tried so many solutions but none work.
No error in console. Just 'on_member_join' doesn't work; ping and console message methods work.
Here is my code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='*')
TOKEN = '----my token here----'
#client.event
async def on_ready():
print('Bot is ready')
#client.event
async def on_member_join(member):
channel = client.get_channel(764960656553934879)
await channel.send('Hello')
#client.command()
async def ping(ctx):
await ctx.send('Pong!')
client.run(TOKEN)
For discord.py 1.5.0, reference the introduction of intents.
Your bot will need the members intent - which happens to be a priveleged intent - in order for the on_member_join event to be triggered properly.

Discord.py: Why do the welcome and goodbye messages repeat?

Problem: I am trying to have it so that the bot sends a single message in general, but the messages continuously repeat, seemingly increasing each time this occurs. Also, if I switch the message to something else, the repeated parts are of the old message.
Code:
import discord
from discord.ext import commands
client=commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print('ok')
#client.event
async def on_member_join(member):
channel=discord.utils.get(member.guild.channels, name="general")
await channel.send("Hi {}".format(member))
#client.event
async def on_member_remove(member):
channel=discord.utils.get(member.guild.channels, name="general")
await channel.send("Bye")
client.run(token)
Since the code is under the function variable then you have to end each function.
It might be due to multiple instances of the application are running. Check your task manager and search for python process, End it if there are multiple and re-run the script.

How to make a discord bot react to PAST private messages?

I made a simple discord.py bot that reacts whenver it is PM'd. However, if someone messages it while my bot is offline, it will not react. How can i make it display all messages received while it was online on startup?
Current code:
import discord
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix='.')
#client.event
async def on_message(message):
if message.guild is None and message.author != client.user:
send_this_console=f'{message.author}: \n{message.content}\n'
print(send_this_console)
await client.process_commands(message)
You'll need to use message history and track the last message sent.
To get when a message was created:
lastMessageTimestamp = message.created_at
You'll need to store this in whatever way you want when your bot is offline (for example with pickle) and do this:
async for message in user.history(after = lastMessageTimestamp):
print(message.content)

Categories