I built a telegram bot but it doesn't work - python-3.x

Hello everyone please I was working on a telegram bot, this bot works fine on my local pc but when I upload the file to my VPS it gives errors.
This a photo of it working on my local PC Photo Link
And here's the code also
from telegram.ext import Updater,CommandHandler
def start(update,context) -> None:
message = update.message
context.bot.send_message(message.chat.id,"hi",parse_mode="markdown")
def main():
updater = Updater("5412956496:AAFkQCS-mKcqUm1PeRV3U8pjqGrN0k1KpI4",use_context=True)
print("Started")
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
if _name_ == "_main_":
main()
But on my VPS it gives me this error
File "app.py", line 2, in <module>
from telegram.ext import Updater,CommandHandler
File "/usr/local/lib/python3.6/dist-packages/telegram/ext/__init__.py", line 31, in <module>
from .updater import Updater
File "/usr/local/lib/python3.6/dist-packages/telegram/ext/updater.py", line 55, in <module>
class Updater(Generic[CCT, UD, CD, BD]):
File "/usr/local/lib/python3.6/dist-packages/telegram/ext/updater.py", line 198, in Updater
dispatcher: Dispatcher[CCT, UD, CD, BD] = None,
File "/usr/lib/python3.6/typing.py", line 682, in inner
return func(*args, **kwds)
File "/usr/lib/python3.6/typing.py", line 1143, in getitem
orig_bases=self.orig_bases)
File "/usr/lib/python3.6/typing.py", line 978, in new
self = super().new(cls, name, bases, namespace, _root=True)
File "/usr/lib/python3.6/typing.py", line 137, in new
return super().new(cls, name, bases, namespace)
File "/usr/lib/python3.6/abc.py", line 133, in new
cls = super().new(mcls, name, bases, namespace, **kwargs)
TypeError: dict slot disallowed: we already got one
I really would appreciate help offered thank you.

You should revoke the bot token that you posted.
Which version of python-telegram-bot are you using? v13.12+ does not support python 3.6.
Disclaimer: I'm currently the maintainer of python-telegram-bot.

Related

Problem starting Telegram bot with pyrogram

Hi i am receiving an error starting a bot with nothing on it yet
I am using Pyrogram (2.0.97) and Python (3.9.6)
I didn't developed more code for this bot yet, but i want to use this library (pyrogram) and not other library, because of this decorators that has on this library
Here is the simple code
from pyrogram import Client, filters
from pyrogram.types import Message
from pyrogram.types import (
InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
)
TELEGRAM_API_ID = "22284blablabla"
TELEGRAM_API_HASH = "186a3759fc29f394bad2700cc29ecblablabla"
TELEGRAM_BOT_TOKEN = "blablablablabla"
app = Client(
'SegBot',
api_id=TELEGRAM_API_ID,
api_hash=TELEGRAM_API_HASH,
bot_token=TELEGRAM_BOT_TOKEN
)
#app.on_message(filters.private)
async def hello(client, message):
await message.reply("Hello from Pyrogram!")
print('running!!!')
app.run()
And the error is:
running!!!
Traceback (most recent call last):
File "G:\Drives compartilhados\SEG FIS\API\TELEGRAM BOT TEST\bot_test.py", line 151, in <module>
app.run()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\methods\utilities\run.py", line 84, in run
self.start()
return loop.run_until_complete(coroutine)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\methods\utilities\start.py", line 58, in start
is_authorized = await self.connect()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\methods\auth\connect.py", line 40, in connect
await self.load_session()
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\client.py", line 586, in load_session
await Auth(
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 254, in create
raise e
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 89, in create
res_pq = await self.invoke(raw.functions.ReqPqMulti(nonce=nonce))
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 67, in invoke
return self.unpack(response)
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\session\auth.py", line 60, in unpack
return TLObject.read(b)
File "C:\Users\roberto.lins\AppData\Roaming\Python\Python39\site-packages\pyrogram\raw\core\tl_object.py", line 33, in read
return cast(TLObject, objects[int.from_bytes(b.read(4), "little")]).read(b, *args)
KeyError: 0
Any help, please?

Telegram bot polling function

This is my first time trying to make a telegram bot.
Code:
import os
import telebot
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)
#bot.message_handler(commands=['hello'])
def send_welcome(message):
bot.reply_to(message, "HI!")
bot.polling()
Error:
Traceback (most recent call last):
File "/Users/anshtyagi/Documents/telegram bot/main.py", line 23, in <module>
bot.polling()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 621, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 695, in __threaded_polling
raise e
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 650, in __threaded_polling
polling_thread.raise_exceptions()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/util.py", line 111, in raise_exceptions
raise self.exception_info
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/util.py", line 93, in run
task(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 360, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1),
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 338, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/apihelper.py", line 324, in get_updates
return _make_request(token, method_url, params=payload)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/apihelper.py", line 80, in _make_request
raise Exception('Bot token is not defined')
Exception: Bot token is not defined
I am getting this error while running my telegram bot this is my first time. I have seen some tutorials how to make a bot but mine is not working. I have posted my token in .env file and imported it using os.getenv. I am just simply trying to make a simple bot just for my knowledge as I have tried making discord bots and it was great experience and I learned many new languages so I thought why not try this also.
I'm also new to python and telegram bots, but my first bot is running ok and I see the problem in your code. Your exception tells us Exception: Bot token is not defined. So your script doesn't get a token from the system var.
You say that you have your token in .env file. To get os variable from that file first of all we must import a module: from dotenv import load_dotenv.
Next we must import variables from that file using the function load_dotenv().
After that we can read our variables with os.getenv. So that line of your code seems to be correct. If there is no variable in the file os.getenv should get it from the os.
So your code may look like:
import os
import telebot
from dotenv import load_dotenv
load_dotenv()
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)
#bot.message_handler(commands=['hello'])
def send_welcome(message):
bot.reply_to(message, "HI!")
bot.polling()
try this:
import telebot
bot = telebot.TeleBot("API_KEY")
instead of:
import os
import telebot
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)

No current context error after Python 3 migration, should I include more logic?

I'm converting a Google App Engine Python 2 project to Python 3
My understanding from reading the documentation I understand the preferred path is to run the main python program directly, skipping dev_appserver.py as was done in the past.
https://cloud.google.com/appengine/docs/standard/python3/tools/local-devserver-command
python3 main.py
--- main.py --
# coding: utf-8
import flask
from flask import request, redirect, url_for
from flask_basicauth import BasicAuth
#from urllib# import urlparse, urlunparse
import config
--- config.py
import model
...
33: CONFIG_DB = model.Config.get_master_db()
--- model/config.py
from __future__ import absolute_import
from google.cloud import ndb
#from oauth2client.contrib.appengine import CredentialsNDBProperty
from api import fields
import config
import model
import util
...
class Config(model.Base, model.ConfigAuth):
...
#classmethod
def get_master_db(cls):
57: return cls.get_or_insert('master')
When running the following trace is prod
Traceback (most recent call last):
File "main.py", line 9, in <module>
import config
File "/home/ffej/cloudpayback/main/config.py", line 33, in <module>
CONFIG_DB = model.Config.get_master_db()
File "/home/ffej/cloudpayback/main/model/config.py", line 57, in get_master_db
return cls.get_or_insert('master')
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/utils.py", line 146, in positional_wrapper
return wrapped(*args, **kwds)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/model.py", line 5698, in _get_or_insert
return cls._get_or_insert_async(
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/utils.py", line 146, in positional_wrapper
return wrapped(*args, **kwds)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/model.py", line 5811, in _get_or_insert_async
key = key_module.Key(cls._get_kind(), name, parent=parent, **key_args)
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/key.py", line 290, in __new__
context = context_module.get_context()
File "/home/ffej/cloudpayback/env/lib/python3.8/site-packages/google/cloud/ndb/context.py", line 96, in get_context
raise exceptions.ContextError()
google.cloud.ndb.exceptions.ContextError: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context.
Is there additional logic that should be included after migration to start/initialize the datastore?
Thanks,
Jeff
The API for NDB library in Python3 has changed significantly. For developing on localhost you have to:
run DataStore Emulator, since you're not running dev_appserver anymore:
$ gcloud beta emulators datastore start
if you use the new NDB Library, then each NDB operation needs to be wrapped in a context manager:
with ndb_client.context(): # <- you need this line
cls.get_or_insert('master')
edit: instead of wrapping each NDB call with a context manager, you can use a middleware which will wrap the whole request cycle into the NDB context:
class NDBMiddleware:
def __init__(self, app):
self.app = app
self.client = ndb_client
def __call__(self, environ, start_response):
with self.client.context():
return self.app(environ, start_response)
app = Flask(__name__)
app.wsgi_app = NDBMiddleware(app.wsgi_app)

MLflow: active run ID does not match environment run ID

OS: Ubuntu 18
Python: Python 3.6
MLflow: 1.4
I'm trying to get MLflow Projects to run. Here is my project:
MLflow
conda.yaml
main.py
prep_data.py
learn.py
List item
The project is heavily based up on this repo: https://github.com/mlflow/mlflow/tree/master/examples/multistep_workflow
I'm trying to run both the prep_data and learn scripts using MLflow Projects and the main.py script as an entry point.
For execution I use the following command: mlflow run . -P experiment_name=testproject
But I get the following Error:
Traceback (most recent call last):
File "prep_data.py", line 126, in <module>
prep_data()
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "prep_data.py", line 65, in prep_data
with mlflow.start_run() as active_run:
File "/home/ubuntu/venv/lib/python3.6/site-packages/mlflow/tracking/fluent.py", line 129, in start_run
"arguments".format(existing_run_id))
mlflow.exceptions.MlflowException: Cannot start run with ID 405b83bbb61046afa83b8dcd71b4db14 because active run ID does not match environment run ID. Make sure --experiment-name or --experiment-id matches experiment set with set_experiment(), or just use command-line arguments
Traceback (most recent call last):
File "main.py", line 75, in <module>
workflow()
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/ubuntu/venv/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "main.py", line 61, in workflow
}, experiment_name)
File "main.py", line 40, in _get_or_run
submitted_run = mlflow.run('.', entry_point=entry_point, parameters=params)
File "/home/ubuntu/venv/lib/python3.6/site-packages/mlflow/projects/__init__.py", line 287, in run
_wait_for(submitted_run_obj)
File "/home/ubuntu/venv/lib/python3.6/site-packages/mlflow/projects/__init__.py", line 304, in _wait_for
raise ExecutionException("Run (ID '%s') failed" % run_id)
mlflow.exceptions.ExecutionException: Run (ID '405b83bbb61046afa83b8dcd71b4db14') failed
2019/11/22 18:51:59 ERROR mlflow.cli: === Run (ID '62c229b2d9194b569a7b2bfc14338800') failed ===
I'm not sure if I understand the error correctly but it seems like it's saying I am using multiple experiments. However I'm fairly certain I am only using 1 (testproject).
Browsing SO and Github issues suggested I'd should set the environment variable MLFLOW_TRACKING_URI but it wasn't stated on how to set that. Thus I tried two different ways:
1) exporting it before running the MLflow project: $ export MLFLOW_TRACKING_URI='http://127.0.0.1:5099'
2) setting it at the beginning of my main.py script using python: os.environ['MLFLOW_TRACKING_URI'] = 'http://127.0.0.1:5099'
Neither had any effect.
Here you can see my project:
main.py
import os
import click
import mlflow
from mlflow.entities import RunStatus
def _already_ran(entry_point, params, experiment_name):
# experiment = mlflow.get_experiment_by_name('{}_{}'.format(experiment_name, entry_point))
experiment = mlflow.get_experiment_by_name(experiment_name)
if experiment == None:
return None
experiment_id = experiment.experiment_id
client = mlflow.tracking.MlflowClient()
all_run_infos = reversed(client.list_run_infos(experiment_id))
match_failed = False
for run_info in all_run_infos
full_run = client.get_run(run_info.run_id)
for p_key, p_val in params:
run_value = full_run.data.params.get(p_key)
if run_value != p_val:
match_failed = True
break
if match_failed:
continue
if run_info.to_proto().status != RunStatus.FINISHED:
continue
return client.get_run(run_info.run_id)
return None
def _get_or_run(entry_point, params, experiment_name, use_cache=True):
existing_run = _already_ran(entry_point, params, experiment_name)
if use_cache and existing_run:
return existing_run
submitted_run = mlflow.run('.', entry_point=entry_point, parameters=params)
return mlflow.tracking.MlflowClient().get_run(submitted_run.run_id)
#click.command()
#click.option("--experiment-name")
#click.option('--prep-data-time-avg', default='placeholder')
#click.option('--prep-data-sensor-id', default='placeholder')
#click.option('--learn-epochs', default=100, type=int)
#click.option('--learn-neurons', default=5, type=int)
#click.option('--learn-layers', default=2, type=int)
def workflow(experiment_name, prep_data_time_avg, prep_data_sensor_id, learn_epochs, learn_neurons, learn_layers):
# mlflow.set_tracking_uri('http://127.0.0.1:5099')
# mlflow.set_experiment(experiment_name)
# with mlflow.start_run() as active_run:
data_run = _get_or_run('prep_data', {
'time_avg': prep_data_time_avg,
'sensor_id':prep_data_sensor_id,
'experiment_name': experiment_name
}, experiment_name)
learn_run = _get_or_run('learn', {
'epochs': learn_epochs,
'neurons': learn_neurons,
'layers': learn_layers,
'prep_data_run_id': data_run.run_id,
'experiment_name': experiment_name,
}, experiment_name)
if __name__ == '__main__':
# os.environ['MLFLOW_TRACKING_URI'] = 'http://127.0.0.1:5099'
workflow()
prep_data.py
#click.command()
#click.option("--experiment-name")
#click.option('--time-avg', default='placeholder')
#click.option('--sensor-id', default='placeholder')
def prep_data(experiment_name, time_avg, sensor_id):
mlflow.set_experiment(experiment_name)
with mlflow.start_run() as active_run:
# logic code of prep_data
if __name__ == '__main__':
prep_data()
I'm happy about any ideas on how to fix this issue.
Thank you very much!
Cheers,
Raphael
You need to provide the same experiment name to the mlflow CLI:
mlflow run . -P experiment_name=testproject --experiment-name testproject
For more details:
https://www.mlflow.org/docs/latest/cli.html#mlflow-run

Tornado HTTPS Package Error

I have a simple example of a Python (3.6) Tornado (4.5.2) server and I am attempting to add ssl certs for testing. I have determined it is finding the key and csr files. Here is what my code looks like with a stack trace following detailing the error. Has anyone run into this or solved it?
import tornado.httpserver
import tornado.ioloop
import tornado.web
class indexHandler(tornado.web.RequestHandler):
def get(self):
self.write("hello")
application = tornado.web.Application([
(r'/', indexHandler),
])
if __name__ == '__main__':
http_server = tornado.httpserver.HTTPServer(application, ssl_options={
"certfile": "cert/ig.csr",
"keyfile": "cert/ig.key",
})
http_server.listen(443)
tornado.ioloop.IOLoop.instance().start()
Running on Python 3.6.4 and the server runs but when the page is accessed as https://localhost, it throws the following exception. What am I missing?
ERROR:asyncio:Exception in callback BaseAsyncIOLoop._handle_events(5, 1)
handle: <Handle BaseAsyncIOLoop._handle_events(5, 1)>
Traceback (most recent call last):
File "/<python path>/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "/<python path>/site-packages/tornado/platform/asyncio.py", line 102, in _handle_events
handler_func(fileobj, events)
File "/<python path>/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/<python path>/site-packages/tornado/netutil.py", line 252, in accept_handler
callback(connection, address)
File "/<python path>/site-packages/tornado/tcpserver.py", line 264, in _handle_connection
do_handshake_on_connect=False)
File "/<python path>/site-packages/tornado/netutil.py", line 551, in ssl_wrap_socket
context = ssl_options_to_context(ssl_options)
File "/<python path>/site-packages/tornado/netutil.py", line 526, in ssl_options_to_context
context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))
ssl.SSLError: [SSL] PEM lib (_ssl.c:3337)
In above error message, /<python path>/ is equal to:
"/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/"
Its because the signature of the you certificate and the key doesn't match.
OK - I found it!! There are several online resources for determining if your certificate file and key match. I used THIS and they did not match. A quick call to Comodo (cert was thru Namecheap and then thru them) and they fixed it.
Lesson: Validate the key and certificate first!

Resources