from aiogram import Bot
import config
def send_message(message):
operator = Bot(config.operator_token)
operator.send_message(config.user_id, message)
def main():
send_message('hi')
I want to send message to user with id from my config.py (config.user_id). But it's not workinkg. I tried many ways for it but I always got an error.
For example like this
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f94a9b62550>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f94a98f8040>,
23065.38)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f94a9b3c400>'
If you use aiogram you must use async/await to send message.
bot = Bot(token=TOKEN)
dp = Dispatcher(bot_init)
#dp.message_handler(commands=['test'])
async def process_start_command(message: types.Message):
await bot.send_message(message.from_user.id, "test message") #like this
#await message.answer("test message")
#or like this
Maybe this?!
import asyncio
from aiogram import Bot
import config
async def send_message(message):
operator = Bot(config.operator_token)
await operator.send_message(config.user_id, message)
def main():
asyncio.run(send_message('hi'))
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from config import TOKEN
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
await message.reply("Hello\nWrite me something!")
#dp.message_handler(commands=['help'])
async def process_help_command(message: types.Message):
await message.reply("Implementation EchoBot")
#dp.message_handler()
async def echo_message(msg: types.Message):
await bot.send_message(msg.from_user.id, msg.text)
if __name__ == '__main__':
executor.start_polling(dp)
Related
My code is returning this error NoneType object has no attribute 'send'
here is my code
import discord
import os
from discord.ext import commands
client = discord.Client()
class Logging(commands.Cog):
"""Sets up logging for you guild"""
def __init__(self, client):
self.bot = client
async def __error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
#commands.Cog.listener()
async def on_message_delete(self, message,):
deleted = embed = discord.Embed(
description=f"Message deleted in {message.channel.mention}", color=0x4040EC
).set_author(name=message.author, url= discord.Embed.Empty, icon_url=message.author.avatar_url)
channel = client.get_channel(888600482317213786)
deleted.add_field(name="Message", value=message.content)
deleted.timestamp = message.created_at
await channel.send(embed=deleted)
def setup(client):
client.add_cog(Logging(client))
I am doing this in my cogs and not in the main.py
channel = client.get_channel(888600482317213786) should be channel = self.bot.get_channel(888600482317213786). Then check if channel is None.
I assume there is no indentation error in your actual code.
import discord
from discord.ext import commands
class AntiCog(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == 1234567891234567:
mention = f'<#!1234567891234567>'
if message.content == mention:
await message.channel.send("grow up")
user = message.author
print(str(user))
print(str(message.content))
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await user.add_roles(muted_role)
else:
return
await self.client.process_commands(message)
def setup(client):
client.add_cog(AntiCog(client))
This's a working code for muting a person if they ping another person, however, I would like to make it a timed mute for 5 min. All of the resources I found were on_command timed mute, however, this's an auto one, how can I do so. thank you!
All you would have to do is add asyncio.sleep, and then remove the role, so:
import discord
from discord.ext import commands
import asyncio
class AntiCog(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == 1234567891234567:
mention = f'<#!1234567891234567>'
if message.content == mention:
await message.channel.send("grow up")
user = message.author
print(str(user))
print(str(message.content))
muted_role = discord.utils.get(message.guild.roles, name="Muted")
await user.add_roles(muted_role)
await asyncio.sleep(300) # you can change the time here
await user.remove_roles(muted_role)
else:
return
await self.client.process_commands(message)
def setup(client):
client.add_cog(AntiCog(client))
Be sure to import asyncio!
I'm trying to get my basic discord bot to display a GIF using python as if a user was sending it from tenor.
I.E: example gif
I managed to get my bot to send a gif file that can be opened and viewed but I want to take it a step further and have it show the gif in chat.
Example
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 == 'hello':
embed = discord.Embed(title="Title", description="Desc", color=0x00ff00) #creates embed
file = discord.File("toodamnbad.gif", filename="image.png")
embed.set_image(url="attachment://image.png")
await message.channel.send(file=file)
client.run('TOKEN')
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import json
import random
bot = commands.Bot(command_prefix="!", case_insensitive=True)
bot.remove_command('help')
#bot.event
async def on_ready():
print("Asuna")
#bot.command(case_insensitive=True)
async def command(ctx, member: discord.Member): # which command it responds to.
image = random.choice(["url", "url", "url"])
embed = discord.Embed(color = 0x303136, description = "text")
embed.set_image(url=image)
await ctx.send(embed=embed)
random gif↑
1 gif ↓
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import json
bot = commands.Bot(command_prefix="!", case_insensitive=True)
bot.remove_command('help')
#bot.event
async def on_ready():
print("Asuna")
#bot.command(pass_context=True)
async def reactions(cxt):
embed = discord.Embed(color = 0x303136, description = "text")
embed.set_image(url='url')
await cxt.send(embed = embed)
i tried to make cog for organize my bot but i have an error that i dont find how to fix. The bot successful find command in cog but when i write the command i have this error:
Could you help me pls ? Here is my code:
import discord
import asyncio
import re
import os
import random
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#Purge
#commands.command()
async def purge(ctx, amount=10):
await ctx.channel.purge(limit=amount)
Your first parameter must be self.
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
#Purge
#commands.command()
async def purge(self, ctx, amount=10):
await ctx.channel.purge(limit=amount)
Add self as parameter in purge function.
async def purge(self,ctx,amount=10):
await ctx.channel.purge(limit=amount)
I'm running a discord.py bot and I want to be able to send messages through the IDLE console. How can I do this without stopping the bot's other actions? I've checked out asyncio and found no way through.
I'm looking for something like this:
async def some_command():
#actions
if input is given to the console:
#another action
I've already tried pygame with no results but I can also try any other suggestions with pygame.
You can use aioconsole. You can then create a background task that asynchronously waits for input from console.
Example for async version:
from discord.ext import commands
import aioconsole
client = commands.Bot(command_prefix='!')
#client.command()
async def ping():
await client.say('Pong')
async def background_task():
await client.wait_until_ready()
channel = client.get_channel('123456') # channel ID to send goes here
while not client.is_closed:
console_input = await aioconsole.ainput("Input to send to channel: ")
await client.send_message(channel, console_input)
client.loop.create_task(background_task())
client.run('token')
Example for rewrite version:
from discord.ext import commands
import aioconsole
client = commands.Bot(command_prefix='!')
#client.command()
async def ping(ctx):
await ctx.send('Pong')
async def background_task():
await client.wait_until_ready()
channel = client.get_channel(123456) # channel ID to send goes here
while not client.is_closed():
console_input = await aioconsole.ainput("Input to send to channel: ")
await channel.send(console_input)
client.loop.create_task(background_task())
client.run('token')