Telegram Bot UNCLOSED CLIENT - python-asyncio

Basically I was doing a small bot for telegram to send pictures from a subreddit, but it gives me an error which I don't know how to fix. Everything where it says (not shown) is something I can't show due to it being something with which anyone could use it under something I created, but I guess you don't really need it.
client_session: <aiohttp.client.ClientSession object at 0x000001555709DD90>```
config.py:
```settings = {
"CLIENT_ID": "(not shown)",
"SECRET_CODE":"(not shown)",
"TOKEN":"(not shown)"
} ```
telegram_bot.py:
```import asyncio
import aiohttp
import config
import asyncpraw
from aiogram import Bot, types
API_TOKEN = config.settings["TOKEN"]
CHANNEL_ID = -1001374273592
bot = Bot(token=API_TOKEN, parse_mode=types.ParseMode.HTML)
reddit = asyncpraw.Reddit(client_id=config.settings["CLIENT_ID"],
client_secret=config.settings["SECRET_CODE"],
user_agent="random_raddit_bot/0.0.1")
mems = []
TIMEOUT = 5
SUBREDDIT_NAME = "memes"
POST_LIMIT = 1
async def send_message(channel_id: int, txt: str):
await bot.send_message(channel_id, text)
async def main():
while True:
await asyncio.sleep(TIMEOUT)
memes_submissions = await reddit.subreddit(SUBREDDIT_NAME)
memes_submissions = memes_submissions.new(limit=POST_LIMIT)
item = await memes_submissions.__anext__()
if item.titles not in mems:
mems.append(item.title)
await send_message(CHANNEL_ID, item.url)
asyncio.get_event_loop().run_until_complete```

Related

discord.py will not execute a command for some reason

whenever I try to type something in discord, the bot will do nothing.
I checked on the discord developer portal if the message intents was on and it was and I also enabled it in the code as you can see above but it still doesn't work
import os
import discord
import random
from keep_alive import keep_alive
from discord.ext import commands
token = 'token'
intents = discord.Intents.all()
intents.members = True
command_prefix = '!'
bot = commands.Bot(command_prefix, intents = intents)
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name='butterflys fly by'))
#bot.command(name='99')
async def nine_nine(ctx):
print("hell world")
brooklyn_99_quotes = [
'I\'m the human form of the 💯 emoji.',
'Bingpot!',
(
'Cool. Cool cool cool cool cool cool cool, '
'no doubt no doubt no doubt no doubt.'
),
]
response = random.choice(brooklyn_99_quotes)
await ctx.send(response)
#bot.event
async def on_member_join(member):
guild = bot.get_guild(781230819414769765)
welcome_channel = guild.get_channel(783371093570355211)
await welcome_channel.send(
f'Welcome to **{guild.name}**, {member.mention} have fun here! ')
keywords = ["e"]
#bot.event
async def on_message(msg):
for i in range(len(keywords)):
if keywords[i] in msg.content:
await msg.channel.purge(limit=1)
await msg.author.send("don't say that!")
keep_alive()

How do I DM a person with Discord.py??? Why won't my code work?

import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print('Running...')
#client.event
async def on_message(message):
while True:
user = client.get_user('user')
await user.send('hi')
I have tried a million variations of this and it won't work.
Why won't send work????????
I just tested this with the latest version of pycord and it works.
import discord
import os
import asyncio
TOKEN = "TOKEN_HERE"
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents, members = True, messages = True, message_content = True)
#client.event
async def on_ready():
print("Running...")
#client.event
async def on_message(message):
user_id = message.author.id
user = await client.fetch_user(user_id)
await user.send("HI")
client.run(TOKEN)
I don't know why you had a while loop in there, I don't think it was needed. I used client.fetch_user as the method for getting the member object and included the intents for messages and members otherwise the bot won't be able to read messages or access member objects. You will need to make sure you have the intents enabled in your developer account for this to work.

I am trying to compare a variable with a set but keep getting errors

I am trying to compare a variable with a set but I keep getting an error
In the code below I am trying to see if the user's ID is in the code of pre determined IDs called "authUsers" but for some reason it isn't working
import discord
client = discord.Client()
authUser = {'usrID1','usrID2','userID3'}
#client.event
async def on_message(message):
if message.content.lower().startswith('.test'):
if True :{
print('rcvd'),
}
if message.author.id in authUser:
print('rcvd')
embed1 = discord.Embed(title='Hello World!')
await message.channel.send(embed=embed1) #this sends and embed saying "hello world" if it runs succesfully
import os
client.run(os.getenv('TOKEN'))
The problem is that user ids are ints, not strs so instead of authUser = {'usrID1','usrID2','userID3'}, you can use authUser = {1, 2, 3}
Put the ids of the users that you want in place of 1, 2, 3.
The code:
import discord
import os
client = discord.Client()
authUser = {1234, 5678, 9012}
#client.event
async def on_message(message):
if message.content.lower().startswith('.test'):
if True :{
print('rcvd'),
}
if message.author.id in authUser:
print('rcvd')
embed1 = discord.Embed(title='Hello World!')
await message.channel.send(embed=embed1) #this sends and embed saying "hello world" if it runs succesfully
client.run(os.getenv('TOKEN'))
I think you could fo with a for loop too:
import discord
client = discord.Client()
authUser = {'usrID1','usrID2','userID3'}
#client.event
async def on_message(message):
if message.content.lower().startswith('.test'):
if True :{
print('rcvd'),
}
for element in authUser:
if message.author.id in element:
print('rcvd')
embed1 = discord.Embed(title='Hello World!')
await message.channel.send(embed=embed1) #this sends and embed saying #"hello world" if it runs succesfully
else:
print(f"auth not succesful with user {element}.")
import os
client.run(os.getenv('TOKEN'))

Python Socket.io event handling

I'm a complete beginner when it comes to socket, so please bear with me if the question seems too trivial for you.
The following is a code that i found on GitLab and I'm trying to understand
import os
import logging
import uuid
import socketio
from aiohttp import web
import sys
sys.path.append('.')
logging.basicConfig(level=logging.WARN,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')
# Home page
async def index(request):
index_file = open('examples/rasa_demo/templates/index.html')
return web.Response(body=index_file.read().encode('utf-8'), headers={'content-type': 'text/html'})
# Action endpoint
async def webhook(request):
"""Webhook to retrieve action calls."""
action_call = await request.json()
try:
response = await executor.run(action_call)
except ActionExecutionRejection as e:
logger.error(str(e))
response = {"error": str(e), "action_name": e.action_name}
response.status_code = 400
return response
return web.json_response(response)
# Web app routing
app = web.Application()
app.add_routes([
web.get('/', index),
web.post('/webhook', webhook),
web.static('/static', 'examples/rasa_demo/static')
])
# Instantiate all bot agents
bots = BotFactory.createAll()
# Websocket through SocketIO with support for regular HTTP endpoints
sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*')
sio.attach(app)
#sio.on('session_request')
async def on_session_request(sid, data):
if data is None:
data = {}
if 'session_id' not in data or data['session_id'] is None:
data['session_id'] = uuid.uuid4().hex
await sio.emit('session_confirm', data['session_id'])
#sio.on('user_uttered')
async def on_user_uttered(sid, message):
custom_data = message.get('customData', {})
lang = custom_data.get('lang', 'en')
user_message = message.get('message', '')
bot_responses = await bots[lang].handle_text(user_message) #await BotFactory.getOrCreate(lang).handle_text(user_message)
for bot_response in bot_responses:
json = __parse_bot_response(bot_response)
await sio.emit('bot_uttered', json, room=sid)
What I'm trying to understand is how do the event handlers catch or events like 'session_request' or'user_uttered' when they were never emitted.
Thank you.

aiohttp websocket and redis pub/sub

i created a simple websocket server using aiohttp . my server reads message from redis pub/sub and sends it to client .
this is my websocket code:
import aiohttp
from aiohttp import web
import aioredis
router = web.RouteTableDef()
#router.get("/ws")
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
sub = request.config_dict["REDIS"]
ch, *_ = await sub.subscribe('hi')
async for msg in ch.iter(encoding='utf-8'):
await ws.send_str('{}: {}'.format(ch.name, msg))
async def init_redis(app):
redis_pool = await aioredis.create_redis_pool('redis://localhost')
app["REDIS"] = redis_pool
yield
redis_pool.close()
await redis_pool.wait_closed()
async def init_app():
app = web.Application()
app.add_routes(router)
app.cleanup_ctx.append(init_redis)
return app
web.run_app(init_app())
my first client can connect to server and receive messages but when i create another client to connect to this endpoint it receive no messages !
what is the problem ? how can i fix this problem?
You need to call create_redis for each client and publish the message to the channel. Otherwise, only the first client will receive the subscribed message.
So, you can edit your code as follows.
import aiohttp
from aiohttp import web
import aioredis
import asyncio
router = web.RouteTableDef()
async def reader(ws, ch):
while (await ch.wait_message()):
await ws.send_str('{}: {}'.format(ch.name, msg))
#router.get("/ws")
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
sub = await aioredis.create_redis_pool('redis://localhost')
pub = await aioredis.create_redis_pool('redis://localhost')
ch, *_ = await sub.subscribe('hi')
asyncio.ensure_future(reader(ws, ch))
async for msg in ws:
await pub.publish('hi', msg)
sub.close()
pub.close()
async def init_app():
app = web.Application()
app.add_routes(router)
return app
web.run_app(init_app())
Please note there may be minor syntax error (e.g. format of the message), but this is the structure that you should follow as it worked for me. I got it to work with my application.

Resources