Telegram.ext bot building - python-telegram-bot

File "c:\Users\21fin\Desktop\Python Learning\trial.py", line 5, in <module>
updater = telegram.ext.updater( Token, use_context = True )
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'module' object is not callable
what should i do?
import telegram.ext
Token = "my bot token"
updater = telegram.ext.updater( Token, use_context = True )
dispatcher = updater.dispatcher
and i exepected the code to compile

Related

Discord.py error AttributeError: 'Client' object has no attribute 'command'

why it no work
`
#Importing stuff
import discord
import os
import random
from discord.ext import commands
#Variables
command_prefix = '!'
intents = discord.Intents.all()
token = 'MTAzOTA3ODMyODcxMzM1NTMwNA.GMKlpL.gLzQ9H6UCaAE7PNeb0Nv-I2cb-e8p-NgZZJydY'
#Client Setup
bot = discord.Client(command_prefix=command_prefix, intents=intents)
#On ready function (startup)
#bot.event
async def on_ready():
print('Online')
#Status Setup
activity = discord.Game(name="Put Status Here", type=3)
await bot.change_presence(activity=activity)
#bot.command()
async def help(ctx):
await ctx.send('baller')
#Run
bot.run(token)
`
i tried a bunch of other stuff but it no worky pls help me
Error:
AttributeError: 'Client' object has no attribute 'command'

'_asyncio.Future' object has no attribute 'create_future'

I am working on building an asyncio.Future integration with my Tornado app so I can request a callback. Essentially, I instantiated a class within a class, this creates a future and adds a callback to the function.
However, when I call this I get a bunch of error messages:
Traceback (most recent call last):
File "/Users/robot/tornado/venv/lib/python3.8/site-packages/tornado/web.py", line 1713, in _execute
result = await result
File "pending/request_seven.py", line 31, in get
await self.scheduleFuture._future(client.fetch('https://books.toscrape.com'), self.on_response)
File "pending/request_seven.py", line 25, in _future
fut = self.create_future()
AttributeError: '_asyncio.Future' object has no attribute 'create_future'
Here is what I have tried with my script:
define('port', default = 9057, help="run port 9060", type=int)
class requestFour(tornado.web.RequestHandler):
class scheduleFuture(asyncio.SelectorEventLoop):
#staticmethod
def unwrapper(fut: asyncio.Future, function):
return function()
def _future(self, fun1 ):
fut = self.create_future()
fut.add_done_callback(func(self.unwrapper, function=fun1))
return fut
async def get(self):
client = tornado.httpclient.AsyncHTTPClient()
await self.scheduleFuture._future(client.fetch('https://books.toscrape.com'), self.on_response)
def on_response(self, response):
body = response.body
self.write(body)
self.finish()
def my_app():
app = tornado.web.Application(handlers = [(r'/', requestFour)])
http_server = tornado.httpserver.HTTPServer(app)
return http_server
async def main():
app = my_app()
app.listen(options.port)
shutdown_event = asyncio.Event()
await shutdown_event.wait()
if __name__ == '__main__':
asyncio.run(main())

Telegram Bot UNCLOSED CLIENT

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```

No route found for path 'call' in using webRTC

I'm trying to make chat application by using websocket and I'm trying to connect to django-channels.
My consumers.py looks like this:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class VideoCallConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_group_name = self.scope['url_route']['kwargs']['room_name']
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
receive_dict = json.loads(text_data)
action = receive_dict['action']
## 147
if action == 'new-offer' or action == 'new-answer':
receiver_channel_name = receive_dict['message']['receiver_channel_name']
receive_dict['message']['receiver_channel_name'] = self.channel_name
await self.channel_layer.send(
receiver_channel_name,
{
'type': 'send.sdp',
'receive_dict': receive_dict,
}
)
return
receive_dict['message']['receiver_channel_name'] = self.channel_name
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'send.sdp',
'receive_dict': receive_dict,
}
)
async def send_sdp(self, event):
receive_dict = event['receive_dict']
this_peer = receive_dict['peer']
action = receive_dict['action']
message = receive_dict['message']
await self.send(text_data=json.dumps({
'peer': this_peer,
'action': action,
'message': message,
}))
My routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/call/<str:room_name>/', consumers.VideoCallConsumer.as_asgi()),
#re_path(r'', consumers.VideoCallConsumer.as_asgi()),
]
My project routing.py:
import os
import call.routing
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
call.routing.websocket_urlpatterns
)
),
})
I tried to name room_group_name with self.scope['url_route']['kwargs']['room_name'].
The problem is, I can't connect to the websocket, my django server says: Exception inside application: No route found for path 'call'.
WebSocket HANDSHAKING /call [127.0.0.1:52045]
Exception inside application: No route found for path 'call'.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__
return await self.application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/routing.py", line 71, in __call__
return await application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/sessions.py", line 47, in __call__
return await self.inner(dict(scope, cookies=cookies), receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/sessions.py", line 263, in __call__
return await self.inner(wrapper.scope, receive, wrapper.send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/auth.py", line 185, in __call__
return await super().__call__(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/middleware.py", line 26, in __call__
return await self.inner(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/routing.py", line 168, in __call__
raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'call'.
WebSocket DISCONNECT /call [127.0.0.1:52045]
I want to know why this error raised
Also I have additional questions. I think send.sdp in consumers.py is a 'message' here, but what does it represent? And what is the structure of receive_dict in comsumers.py? receivedict['message']['receiverchannelname'] = self.channelname is in consumers.py and self.channel_name is not declared, but why is it working?

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.

Resources