I have same error in python code when i start code
I try write telegram bot with python-telegram-bot
This is my code :
from telegram.ext import Updater , CommandHandler , CallbackContext
from telegram import Update
from telegram.chataction import ChatAction
#bot API
token = "*********:*************" #Im hide API
#bot commands and messages
messages_and_commands = {
"start" : "Hello {} {} wellcome to my bot !"
}
def start_bot(update : Update , context : CallbackContext):
chat_id = update.message.chat_id
first_name = update.message.chat.first_name
last_name = update.message.chat.last_name
context.bot.send_chat_action(chat_id=chat_id , action = ChatAction)
context.bot.send_message(chat_id=chat_id , text=messages_and_commands["start"].format(first_name , last_name))
#bot to can start in the telegram
updater = Updater(token=token , use_context=True)
#set command handler
start_robot = CommandHandler('start' , start_bot)
#add dispatcher
updater.dispatcher.add_handler(start_robot)
#start polling to while start
updater.start_polling()
#when i use ctrl+c the bot is finish action in telegram
updater.idle()
And this is my error in when i start bot:
No error handlers are registered, logging exception.
Traceback (most recent call last):
File "/home/hsahfodsauhfda/env/lib/python3.8/site-packages/telegram/ext/dispatcher.py", `line 432, in process_update`
handler.handle_update(update, self, check, context)
File "/home/hsahfodsauhfda/env/lib/python3.8/site-packages/telegram/ext/handler.py", line `156, in handle_update`
return self.callback(update, context)
File "telegram_bot.py", line 16, in start_bot
context.bot.send_chat_action(chat_id=chat_id , action = ChatAction)
File "<decorator-gen-20>", line 2, in send_chat_action
File "/home/hsahfodsauhfda/env/lib/python3.8/site-packages/telegram/bot.py", line 135, in `decorator`
result = func(*args, **kwargs)
File "/home/hsahfodsauhfda/env/lib/python3.8/site-packages/telegram/bot.py", line 1880, in `send_chat_action`
result = self._post('sendChatAction', data, timeout=timeout, api_kwargs=api_kwargs)
File "/home/hsahfodsauhfda/env/lib/python3.8/site-packages/telegram/bot.py", line 245, in `_post`
return self.request.post(f'{self.base_url}/{endpoint}', data=data, timeout=timeout)
File "/home/hsahfodsauhfda/env/lib/python3.8/site-packages/telegram/utils/request.py", `line 352, in post`
body=json.dumps(data).encode('utf-8'),
File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.8/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
I've tried out the code you pasted here locally. Indeed, once I launch the bot and call the "start" handler I get the same error.
If we have a closer look at the error message we can see this line from your code:
context.bot.send_chat_action(chat_id=chat_id , action = ChatAction)
According to the docs, telegram.ChatAction is a "class to provide constants for different chat actions.", hence if you wish to reference a ChatAction you need to explicitly mention one, like ChatAction.TYPING.
So in your case, if you use the send_chat_action function like this:
context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING)
You should not get the error.
Let me know if it helped!
Related
I was making a telegram bot that would make requests to the ChatGPT neural network and output answers to the user, while all users would initially have 5 trial questions, and in order to do more they should invite a friend 1 friend = 5 questions
Packages:
telebot,
requests,
pyTelegramBotAPI
`
import telebot
import requests
bot = telebot.TeleBot('MY TOKEN')
#Dictionary to store user requests
user_requests = {}
#Function to generate referral link
def generate_referral_link(user_id):
return f'https://example.com/referral?user_id=%7Buser_id%7D'
#Function to make request to ChatGPT
def make_request(user_id, message):
# Make request to ChatGPT
response = requests.post('https://example.com/chatgpt ', data={'user_id': user_id, 'message': message})
# Return response
return response.json()\['response'\]
#Handle /start command
#bot.message_handler(commands=\['start'\])
def start(message):
#Generate referral link
referral_link = generate_referral_link(message.from_user.id)
# Send message
bot.send_message(message.chat.id, f'Hello! You can make up to 5 requests. To get more requests, share this link with your friends: {referral_link},\\nCreated&Developed by #IntelCoreI5 (RqSoulSS)')
# Add user to dictionary
user_requests\[message.from_user.id\] = 0
#Handle all other messages
#bot.message_handler(func=lambda message: True)
def echo_message(message):
# Check if user is in dictionary
if message.from_user.id in user_requests:
# Check if user has requests left
if user_requests\[message.from_user.id\] \< 5:
# Make request
response = make_request(message.from_user.id, message.text)
# Send response
bot.send_message(message.chat.id, response)
# Increment user requests
user_requests\[message.from_user.id\] += 1
else:
# Send message
bot.send_message(message.chat.id, 'You have no more requests left. Share this link with your friends to get more requests: ' + generate_referral_link(message.from_user.id))
else:
# Send message
bot.send_message(message.chat.id, 'Please use /start command first.')
#Run bot
bot.polling()`
with the start command, everything goes fine, but when sending a request, the code crashes
output:
`Traceback (most recent call last):
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\requests\\models.py", line 971, in json
return complexjson.loads(self.text, \*\*kwargs)
File "C:\\Program Files\\Python310\\lib\\json\__init_\_.py", line 346, in loads
return \_default_decoder.decode(s)
File "C:\\Program Files\\Python310\\lib\\json\\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=\_w(s, 0).end())
File "C:\\Program Files\\Python310\\lib\\json\\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\main.py", line 51, in \<module\>
bot.polling()
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\telebot\__init_\_.py", line 1043, in polling
self.\__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\telebot_init_.py", line 1118, in \__threaded_polling
raise e
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\telebot_init_.py", line 1074, in \__threaded_polling
self.worker_pool.raise_exceptions()
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\telebot\\util.py", line 148, in raise_exceptions
raise self.exception_info
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\telebot\\util.py", line 91, in run
task(\*args, \*\*kwargs)
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\telebot_init_.py", line 6428, in \_run_middlewares_and_handler
result = handler\['function'\](message)
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\main.py", line 38, in echo_message
response = make_request(message.from_user.id, message.text)
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\main.py", line 18, in make_request
return response.json()\['response'\]
File "C:\\Users\\MSI\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages\\requests\\models.py", line 975, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Process finished with exit code 1`
I tried changing the url, googling, but nothing happened
import discord
from discord.ext import commands
import random
import praw
cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
client_secret = "",
username = "",
password = "",
user_agent = "")
#cl.event
async def on_ready():
print("Bot is ready, get ready to do wutever u want with it")
#cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
all_submission = []
subreddit = reddit.subreddit("subr")
subs = subreddit.filter(limit = amount)
for submission in subs:
all_submission.append(submission)
random_sub = random.choice(all_submission)
name = random_sub.title
url = random_sub.url
em = discord.embed(title = name)
em.set_image = url
await ctx.send(embed=em)
print("embed sent")
cl.run("")
when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 20, in meme
subs = subreddit.filter(limit = amount)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
self._fetch()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
data = self._fetch_data()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
return self._reddit.request("GET", path, params)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
return self._core.request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
return self._request_with_retries(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
self._request_token(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request
This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed
This doesn't appear to be a discord.py issue, it appears to be related to the praw 0auth flow.
According to the traceback, there's an authentication issue in your praw credentials. Double, triple, and quadruple check your authentication credentials and flow with the workflow and methodology in the docs
i started learning new stuff about programming a bot in Telegram so i wrote my first lines, but when it comes to giving it a try i keep getting some errors so here is my code and the erros i keep getting ...
import telebot , config , os
API_KEY = os.getenv("API_KEY")
bot = telebot.TeleBot(API_KEY)
#bot.message_handler(commands=['Greet'])
def greet(message):
bot.reply_to(message,"Hey, how's it going?")
bot.polling()
after i run it i get this :
Traceback (most recent call last):
File "C:\Users\raccoon\Desktop\Coding room\Python 3.9\TelegramBot\main.py", line 12, in <module>
bot.polling()
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\__init__.py", line 496, in polling
self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout)
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\__init__.py", line 555, in __threaded_polling
raise e
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\__init__.py", line 517, in __threaded_polling
polling_thread.raise_exceptions()
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\util.py", line 87, in raise_exceptions
raise self.exception_info
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\util.py", line 69, in run
task(*args, **kwargs)
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\__init__.py", line 322, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout, long_polling_timeout = long_polling_timeout)
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\__init__.py", line 292, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\apihelper.py", line 281, in get_updates
return _make_request(token, method_url, params=payload)
File "C:\Users\raccoon\AppData\Local\Programs\Python\Python39\lib\site-packages\telebot\apihelper.py", line 76, in _make_request
logger.debug("Request: method={0} url={1} params={2} files={3}".format(method, request_url, params, files).replace(token, token.split(':')[0] + ":{TOKEN}"))
AttributeError: 'NoneType' object has no attribute 'split'
[Finished in 1.3s]
i literally have no idea how to get through this, please if someone could help!
From what I can see from the error seems like you API_TOKEN is not on the environment of your computer.
You have two (?) options:
Add the API_TOKEN in yor environment, in the case of windows this can be done using set API_TOKEN your_api_key or export API_TOKEN=your_api_key on Linux
Change your code harcoding the API_KEY directly
API_KEY = your_api_key
bot = telebot.TeleBot(API_KEY)
you need to load your environment variables first from .env file in the root directory of your project, use python-dotenv.
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("API_KEY")
this should work.
I tried to make a simple translate funcion in my Discord Bot and got to this Error:
Ignoring exception in command translate:
Traceback (most recent call last):
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Luca\Documents\Discord\cogs\translate.py", line 30, in translate
await msg.send(embed=new_emd, delete_after=20)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 904, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 156, in request
kwargs['data'] = utils.to_json(kwargs.pop('json'))
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 318, in to_json
return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Translated is not JSON serializable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Translated is not JSON serializable
I already looked it up, but i found no solutions. Because it is in the library i don't know what to do about it. Please help me.
This is the code i wrote:
from googletrans import Translator
import discord
from discord.ext import commands
#commands.command(pass_context=True)
async def translate(self, msg, lang, *,args):
"""Translates words from one language to another.
Usage:
-translate 'language' 'text'
Language example: 'fr' 'en'
"""
#To Check if it has the delete Messages Permission
try:await msg.message.delete()
except:
embed = discord.Embed(
colour=discord.Colour(0x1))
embed.add_field(name="I don't have the permissions to do that!",
value="please give me the 'Manage Messages' permission")
return await msg.send(embed=embed, delete_after=30)
#Simple Translator | Read on the googletrans page
t = Translator(service_urls=['translate.google.com'])
text = t.translate(args, dest=lang)
#Posts Embed with the Text and also the Language
new_emd = discord.Embed(title="Broski Translator in " + lang, description=text, colour=discord.Colour(0x1))
await msg.send(embed=new_emd, delete_after=20)
This seems to be a recurring error in googletrans package.
In this answer by #Maldus you can see a work-around to fix this issue.
Or you can try installing the new alpha version which is supposed to correct this:
pip install googletrans==3.1.0a0
Im working on a slack bot using the new slack 2.0 python library. I am new to python decorators and I suspect that is part of my problem.
Here is my code...
#!/opt/rh/rh-python36/root/usr/bin/python
import os
import slack
# instantiate Slack client
slack_token = os.environ['SLACK_BOT_TOKEN']
rtmclient = slack.RTMClient(token=slack_token)
webclient = slack.WebClient(token=slack_token)
# get the id of my user
bot_id = webclient.auth_test()['user_id']
print('Bot ID: {0}'.format(bot_id))
def get_user_info(user_id):
user_info = webclient.users_info(user=user_id)['ok']
return user_info
#slack.RTMClient.run_on(event='message')
def parse_message(**payload):
data = payload['data']
user_id = data['user']
print(get_user_info(user_id))
rtmclient.start()
It outputs the Bot ID(using the webclient) when started but then crashes with RuntimeError: This event loop is already running when I make another call to webclient.
[root#slackbot-01 bin]# scl enable rh-python36 /root/slackbot/bin/slackbot.py
Bot ID: UBT547D31
Traceback (most recent call last):
File "/root/slackbot/bin/slackbot.py", line 24, in <module>
rtmclient.start()
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/rtm/client.py", line 197, in start
return self._event_loop.run_until_complete(future)
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/asyncio/base_events.py", line 467, in run_until_complete
return future.result()
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/rtm/client.py", line 339, in _connect_and_read
await self._read_messages()
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/rtm/client.py", line 390, in _read_messages
await self._dispatch_event(event, data=payload)
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/rtm/client.py", line 440, in _dispatch_event
self._execute_in_thread(callback, data)
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/rtm/client.py", line 465, in _execute_in_thread
future.result()
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/concurrent/futures/_base.py", line 425, in result
return self.__get_result()
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/root/slackbot/bin/slackbot.py", line 22, in parse_message
print(get_user_info(user_id))
File "/root/slackbot/bin/slackbot.py", line 15, in get_user_info
user_info = webclient.users_info(user=user_id)
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/web/client.py", line 1368, in users_info
return self.api_call("users.info", http_verb="GET", params=kwargs)
File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/slack/web/base_client.py", line 154, in api_call
return self._event_loop.run_until_complete(future)
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/asyncio/base_events.py", line 454, in run_until_complete
self.run_forever()
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/asyncio/base_events.py", line 408, in run_forever
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
The really confusing part to me is that if I comment out the line that makes the first call to webclient.auth_test(), I have no issues at all. My call to webclient.users_info() works every time rtmclient sends me data.
#!/opt/rh/rh-python36/root/usr/bin/python
import os
import slack
# instantiate Slack client
slack_token = os.environ['SLACK_BOT_TOKEN']
rtmclient = slack.RTMClient(token=slack_token)
webclient = slack.WebClient(token=slack_token)
# get the id of my user
#bot_id = webclient.auth_test()['user_id']
#print('Bot ID: {0}'.format(bot_id))
def get_user_info(user_id):
user_info = webclient.users_info(user=user_id)['ok']
return user_info
#slack.RTMClient.run_on(event='message')
def parse_message(**payload):
data = payload['data']
user_id = data['user']
print(get_user_info(user_id))
rtmclient.start()
[root#slackbot-01 bin]# scl enable rh-python36 /root/slackbot/bin/slackbot.py
True
True
^C[root#slackbot-01 bin]#
I need to get the bot id so that I can make sure it doesnt answer it's own messages. I don't why my code doesnt work after I get the bot id outside of the parse message function with a decorator.
What am I doing wrong here?
The python event loop is a tricky thing to program libraries around and there are some issues with the way the event queue is managed in the 2.0 version of SlackClient. It looks like some improvements were made with 2.1 but it appears to be a work in progress, and I still encounter this. I'd expect there will be future updates to make it more robust.
In the meantime, the following code at the top of your file (use pip to install) usually resolves it for me:
import nest_asyncio
nest_asyncio.apply()
Keep in mind this will alter the way the rest of your application is handling the event queue, if that's a factor.
If you're using RTM, the RTMClient creates a WebClient for you. The handle for it should be getting passed to you in the payload when you handle an event. You can check your ID by looking for the 'open' event which is always dispatched after RTM successfully connects and doing the lookup inside your 'open' event handler.