Python send message to multiple channels - python-3.x

Hello i want to send a message to multiple channels using channel id's from any server.
I used below code its working fine for a single channel.
#bot.command(pass_context=True)
async def ping(ctx):
channel = bot.get_channel("1234567890")
await bot.send_message(channel, "Pong")
But when i try to add multiple channel id's i getting error TypeError: get_channel() takes 2 positional arguments but 3 were given when i use like below.
channel = bot.get_channel("1234567890", "234567890")

get_channel takes a single argument. You need to loop over all the IDs and send a message to each individually.
#bot.command(pass_context=True)
async def ping(ctx):
channels_to_send = ["1234567890", "234567890"]
for channel_id in channels_to_send:
channel = bot.get_channel(channel_id)
await bot.send_message(channel, "Pong")

Related

Discord.py - Sending to multiple channels

I have a working bot that sends posts from my discord server to another. I'm looking for a way to add additional channels of other servers but can't figure out how to get it to work. I read somewhere that get_channel only works once and that I need to incorporate it into a loop? I'm new to python and discord.py so most likely I just don't understand. Here's my code, Hopefully, someone can help.
import discord
intents = discord.Intents(messages=True, guilds=True)
from discord.ext import commands
test001from=1029028218684055562
test001to=1028777554217291806, 1028777583808098304
bot = commands.Bot(command_prefix = ".");
#bot.event
async def on_ready():
print("Bot Active")
#bot.event
async def on_message(message):
if message.channel.id == test001from:
channeltosend = bot.get_channel(test001to)
await channeltosend.send(message.content)
bot.run("TOKEN")
First, put all the channel ids into a list like so: test001to[1028777554217291806, 1028777583808098304]
Second, use get_channel in the on_ready function and save them as a new list.
Third, use a for loop to iterate through the new list you created for chan in channels and send the message to each channel chan.send(message.content).

Echo a message from another app in discord

I have a bot running in a separate app, but there is a specific variable holding data that I want to also be echo'd on my discord server. The bot itself is huge, but I can pin the specific method here
import discord
import asyncio
import rpChat
global note
class EchoBot(rpChat.ChatClient):
def on_PRI(self, character, message):
super().on_PRI(character, message)
note = character + ": " + message
global note
if message[:1] == "~":
super().PRI("A GameMaster", note)
to try to send this message to discord, I have the following. This is not put in the class above, but just below it, and is not in a class itself:
client = discord.Client()
async def discordEcho():
"""Background task that sends message sent from chat to an appropriate Discord channel
when global messege data is updated"""
await client.wait_until_ready()
channel = client.get_channel(serverroom}
while not client.is_closed():
global note
await channel.send(channel, note)
The data to grab the channel IDs are found in a json
file = open("credentials.json", "r", encoding="utf-8")
info = json.load(file)
file.close()
token = info["discord"]
serverroom = info["serverroom"]
client.loop.create_task(discordEcho())
client.run(token)
When I try this, I obtain:
await client.send_message(channel, message)
AttributeError: 'Client' object has no attribute 'send_message'
And I am unsure why. I have built a bot for both this chat platform, and for discord, but this is the first time I've ever attempted to bridge messages between the two. I am sure what I have offered is clear as mud, but any help would be appreciated, if possible.
Edit:
Edited changes to code. It is working thanks to comment below.
client.send_message is an old, outdated method, it has been replaced with Messageable.send
async def discordEcho():
"""Background task that sends message sent from chat to an appropriate Discord channel
when global messege data is updated"""
await client.wait_until_ready()
channel = client.get_channel(serverroom)
while not client.is_closed():
global note
await channel.send(note)
Side note: you first need to wait_until_ready before getting the channel to wait until the cache is done loading, otherwise channel will be None

Python3 + Discord - Send a message each X seconds

I am trying to create a Discord bot that would automatically send a message each X seconds (every 3 seconds, for example) without any user interaction/command input.
This is the code that I have:
import discord
from discord.ext import tasks, commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
await bot.wait_until_ready()
print("Logged in as:")
print(bot.user.name)
print("------")
channel = bot.get_channel(IDasInteger)
print("Channel is:")
print(channel) #Prints None
get_price.start()
#tasks.loop(seconds=3)
async def get_price():
await bot.wait_until_ready()
channel = bot.get_channel(IDasInteger)
print("Channel is:")
print(channel) #Prints None
await channel.send('Test')
#get_price.before_loop
async def before ():
print("Before done.")
bot.run('MyTokenHere')
The problem is, that when I execute this code, it gives me the following error:
AttributeError: 'NoneType' object has no attribute 'send'
When I try to print the channel variable it returns None.
The Channel ID is correct - I have copied it directly from Discord app without any alterations to its value.
Any ideas, please?
Thank you
The reason you are getting None is that IDasInteger is not defined (at least in the code you provided. If it is defined in your code then it cannot find the channel and returns None. None does not have the attribute send and the error is raised.
Change the channel id to the id of a valid channel in your server.
functions channel = bot.get_channel(790279425633758682)
Or make sure the IDasInteger is returning a valid channel ID
Note: I tested the code with a valid channel id to my server and it worked as intended.

How to get how many messages has been sent in a channel

I am trying to get the number of how many messages have been sent in a channel, and using the logs_from() function wont work because that only accepts a fixed amount of messages to retrieve, how do I do this?
In the discord.py-rewrite branch, there is a TextChannel.history AsyncIterator. If you pass limit=None, it will return all the messages from the channel
#bot.command()
async def message_count(ctx, channel: discord.TextChannel=None):
channel = channel or ctx.channel
count = 0
async for _ in channel.history(limit=None):
count += 1
await ctx.send("There were {} messages in {}".format(count, channel.mention))
You might try passing limit=None to logs_from, but it isn't documented as working that way like it is in the rewrite branch.

Delete all the bot's messages in a channel

I am trying to create a command in my bot that will delete all the bot's messages only. Is there a way to iterate through all the channel's messages and if it is a message the bot sent, the bot would delete it? I've understood delete_message but I can't figure out how to iterate through all the channel's messages, if that is even possible.
The following code wouldn't iterate through all the channel's messages, but it would delete the message if the author ID is 383804325077581834:
#bot.event
async def on_message(message):
if message.author.id == '383804325077581834':
await bot.delete_message(message)
383804325077581834 is my bot's ID. So I would like to know how I can iterate through all channel messages and delete those that were sent by my bot. Thank you so much!
EDIT: Tried doing this:
#bot.command(pass_context=True)
async def delete(ctx, number):
msgs = []
number = int(number)
async for msg in bot.logs_from(ctx.message.channel, limit=number):
if msg.author.id == '383804325077581834':
msgs.append(msg)
await bot.delete_messages(msgs)
But I get the error discord.ext.commands.errors.MissingRequiredArgument: number is a required argument that is missing.
#bot.command(pass_context=True)
async def delete(ctx):
msgs = []
async for msg in bot.logs_from(ctx.message.channel):
if msg.author.id == '383804325077581834':
msgs.append(msg)
await bot.delete_messages(msgs)
The command you tried using needed a number parameter which would delete that number of messages from the channel.
The logs_from function will delete all messages from that channel if the limit is not passed into it.
EDIT: Forgot to remove number, whoops.

Resources