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
Related
I create a bot that notifies the user at certain times, but from time to time gives this error
dispatcher.py [LINE:390] ERROR | 2022-10-03 04:10:16,846 : Cause exception while getting updates.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.py", line 381, in start_polling
updates = await self.bot.get_updates(
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
result = await self.request(api.Methods.GET_UPDATES, payload)
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 128, in check_result
raise exceptions.TelegramAPIError(description)
aiogram.utils.exceptions.TelegramAPIError: Bad Gateway
I think this problem is on the telegram side itself and is solved via webhook, but I don't want to use them.
I've been banging my head against my keyboard for a day now, so I'm giving up and asking for help.
I've got a working consumer using confluence kafka, but I need to make it run as a coroutine so I can get things working with FastAPI. I really wanted to try out AIOKafka for this, but for the life of me, I can't get it to work with a self-signed certificate (this is in our dev env).
Here is the working config for my confluence kafka consumer:
conf = {
"bootstrap.servers": "10.142.252.214:9093",
"group.id": "myConsumerID",
"security.protocol": "SASL_SSL",
"sasl.username": kafkaUser,
"sasl.password": kafkaPass,
"sasl.mechanisms": "PLAIN",
"enable.ssl.certificate.verification": "False",
"on_commit": commit_completed,
"heartbeat.interval.ms": "1000",
"socket.connection.setup.timeout.ms": "10000",
"auto.offset.reset": "earliest"
}
Here is the code I'm trying to use for AIOKafka
async def consume():
cert = "../foo/cert/certificate.pem"
key = "../foo/cert/key.pem"
context2 = ssl.create_default_context()
context2.load_cert_chain(certfile=cert, keyfile=key)
context2.check_hostname = False
context2.verify_mode = CERT_NONE
#context2.ssl_cafile="../foo/cert/CARoot.pem"
context2.ssl_certfile = "cert.pem"
context2.ssl_keyfile = "key.pem"
context2.ssl_password = kafkaKey
context2.ssl_keystore_type = "PEM"
consumer = AIOKafkaConsumer(
'TopicA', 'TopicB',
bootstrap_servers="10.142.252.214:9093",
group_id="myConsumerGroup",
sasl_plain_username="kafkaUser",
sasl_plain_password="kafkaPass",
sasl_mechanism="PLAIN",
security_protocol="SASL_SSL",
ssl_context=context2)
await consumer.start()
try:
# Consume messages
async for msg in consumer:
print("consumed: ", msg.topic, msg.partition, msg.offset,
msg.key, msg.value, msg.timestamp)
finally:
# Will leave consumer group; perform autocommit if enabled.
await consumer.stop()
When I try to run this, I just get the most cryptic errors ever and I can't make any sense on where to start trying to figure out what's wrong.
$ python test-main.py
Traceback (most recent call last):
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 375, in _on_read_task_error
read_task.result()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 518, in _read
resp = await reader.readexactly(4)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/streams.py", line 706, in readexactly
raise exceptions.IncompleteReadError(incomplete, n)
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 4 expected bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 165, in <module>
asyncio.run(consume())
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 155, in consume
await consumer.start()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/consumer/consumer.py", line 346, in start
await self._client.bootstrap()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/client.py", line 210, in bootstrap
bootstrap_conn = await create_conn(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 96, in create_conn
await conn.connect()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 234, in connect
await self._do_sasl_handshake()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 314, in _do_sasl_handshake
auth_bytes = await self._send_sasl_token(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
return fut.result()
kafka.errors.KafkaConnectionError: KafkaConnectionError: Connection at 10.142.252.214:9093 closed
Unclosed AIOKafkaConsumer
consumer: <aiokafka.consumer.consumer.AIOKafkaConsumer object at 0x107338670>
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 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!
So I'm trying to program a Reddit reply bot to simply moderating and i got pretty far into it but then when testing the code python gave me a long error that I don't understand. I haven't tried fixing it much because my skill on python is very limited so I have no idea what to do.
import praw
userAgent = 'Recomend Bot 0.1'
cID = 'rz8Gh2k8RS-NRA'
cSC= '9FR8Balfkd0OcgiKVosMSqAP2YM'
userN = ''
userP =''
numFound = 0
reddit = praw.Reddit(user_agent=userAgent, client_id=cID, client_secret=cSC, username=userN, password=userP)
subreddit = reddit.subreddit('empfehlen_testen')
bot_phrase = 'Test Reply 177013'
keywords = {'test', 'Test', 'recomendation'}
for submission in subreddit.new(limit=10):
n_title = submission.title.lower()
for i in keywords:
if i in n_title:
numFound = numFound + 1
print('Bot replying to: ')
print("Title: ", submission.title)
print("Text: ", submission.selftext)
print("Score: ", submission.score)
print("---------------------------------")
print('Bot saying: ', bot_phrase)
print()
submission.reply(bot_phrase)
if numFound == 0:
print()
print("Sorry, didn't find any posts with those keywords, try again!")
#credit for code goes to Phrynk for code all I did was get it to work on my coumputer
That got working somehow and then this error message popped up
Traceback (most recent call last):
File "C:\Users\Dillon\Desktop\RedditBot\reddit_bot.py", line 26, in <module>
for submission in subreddit.new(limit=10): #this views the top 10 posts in that subbreddit
File "C:\Users\Dillon\Desktop\RedditBot\praw\models\listing\generator.py", line 52, in __next__
self._next_batch()
File "C:\Users\Dillon\Desktop\RedditBot\praw\models\listing\generator.py", line 62, in _next_batch
self._listing = self._reddit.get(self.url, params=self.params)
File "C:\Users\Dillon\Desktop\RedditBot\praw\reddit.py", line 446, in get
data = self.request("GET", path, params=params)
File "C:\Users\Dillon\Desktop\RedditBot\praw\reddit.py", line 581, in request
method, path, data=data, files=files, params=params
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\sessions.py", line 185, in request
params=params, url=url)
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\sessions.py", line 116, in _request_with_retries
data, files, json, method, params, retries, url)
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\sessions.py", line 101, in _make_request
params=params)
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\rate_limit.py", line 35, in call
kwargs['headers'] = set_header_callback()
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\sessions.py", line 145, in _set_header_callback
self._authorizer.refresh()
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\auth.py", line 328, in refresh
password=self._password)
File "C:\Users\Dillon\AppData\Local\Programs\Python\Python37-32\lib\site-packages\prawcore\auth.py", line 142, in _request_token
payload.get('error_description'))
prawcore.exceptions.OAuthException: invalid_grant error processing request
prawcore.exceptions.OAuthException: invalid_grant error processing request
means there was a problem authenticating the user.
Remember that the username is your reddit's account name, not the bot's name.