I have an issue with my bot:
I want to authorize user via phone_request. But it crashes. Although I get user phone. By phone_request I mean that I'm asking user for a phone number with this:
def get_keyboard():
contact_button = KeyboardButton('Start conversation',
request_contact=True)
reply_keyboard = [[contact_button]]
return reply_keyboard
I catch it with this:
dp.add_handler(MessageHandler(Filters.contact,
contact_callback,pass_user_data=True))
Than it goes there:
def contact_callback(bot, update):
contact = update.effective_message.contact
phone = contact.phone_number
print(contact)
print(phone)
update.message.reply_text('Thanks your data is accepted', get_authorized(), resize_keyboard=True)
get_authorized is simply this:
def get_authorized():
reply_keyboard = [['Pay', 'Why I'm in debt'], ['Remind Later']]
return reply_keyboard
What can go wrong here?
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/telegram/ext/dispatcher.py", line 279, in process_update
handler.handle_update(update, self)
File "/usr/local/lib/python3.5/dist-packages/telegram/ext/messagehandler.py", line 169, in handle_update
return self.callback(dispatcher.bot, update, **optional_args)
File "/home/ubuntu/Telegram_bot_OSDI/Telegram_Bot_OSDI_22.py", line 164, in contact_callback
update.message.reply_text('Спасибо! Ваши данные приняты', get_authorized(), resize_keyboard=True)
File "/usr/local/lib/python3.5/dist-packages/telegram/message.py", line 455, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/telegram/bot.py", line 65, in decorator
result = func(self, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/telegram/bot.py", line 90, in decorator
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "/usr/local/lib/python3.5/dist-packages/telegram/utils/request.py", line 309, in post
headers={'Content-Type': 'application/json'})
File "/usr/local/lib/python3.5/dist-packages/telegram/utils/request.py", line 223, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Unsupported parse_mode
Related
I am trying to make a quiz bot for training Irregular English Verbs.
The bot should work in a following way:
It sends a message with a line of the poem with an irregular verb in Russian language.
When a man responds it with a message, it should compare a text of a message with the right answer.
If the answer is correct, bot should send a message and than give another question.
After 5 attempts it should give the final result.
I made a QuizStarter object that gives the 'Hello' message. And then closes the process.
class QuizStarter(telepot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(QuizStarter, self).__init__(*args, **kwargs)
def on_chat_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Random Verb', callback_data='Random Verb')],
])
self.sender.sendMessage('Hello. Choose the game below:', reply_markup=keyboard)
self.close()
After that I created Quizzer object that plays the main thing
class Quizzer(telepot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(Quizzer, self).__init__(*args, **kwargs)
self.attempts = 5
self.score = 0
self._answer = None
self.guess = None
def on_callback_query(self, msg):
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
print(query_id, from_id, query_data)
self.show_question()
def show_question(self):
with open('IrregularVerbs.txt', 'r', encoding="utf8") as f:
IrrVerbsStory = f.read()
f.close()
IrrVerbsDict = {}
ReText = re.compile('[a-zA-z]+-[a-zA-z]+-[a-zA-z]+')
result1 = ReText.findall(IrrVerbsStory)
IrrVerbsStory1 = IrrVerbsStory.split(sep='\n')
for i in result1:
for n in IrrVerbsStory1:
if i in n:
IrrVerbsDict[i] = n
IrrVerbsStory1.remove(n)
break
randomDictLine = random.choice(list(IrrVerbsDict.values()))
for x in IrrVerbsDict.keys():
if x in randomDictLine:
time.sleep(1)
self._answer = x.lower()
resultLine = randomDictLine.replace(x, '()')
self.sender.sendMessage(text=f'Please write a nessessary verbs with dashes: {resultLine}\n')
def on_chat_message(self, msg):
self.guess = msg['text']
if self.guess.lower().lstrip() == self._answer.lower().lstrip():
self.score +=1
self.sender.sendMessage(id, f'Good Job! Your score is {self.score}')
else:
self.sender.sendMessage(id, f'Wrong! The right answer is {self._answer} \n')
But whenever I am trying to send a message, it poses an error:
Traceback (most recent call last):
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\delegate.py", line 265, in wait_loop
j.on_message(msg)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\helper.py", line 689, in augmented
return handler(msg)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\helper.py", line 1067, in on_message
self._router.route(msg)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\helper.py", line 1041, in route
return fn(msg, *args, **kwargs)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\helper.py", line 1050, in <lambda>
'callback_query': lambda msg: self.on_callback_query(msg),
File "c:\Users\Growing\Desktop\PythonScripts\Telebot Bot.py", line 38, in on_callback_query
self.show_question()
File "c:\Users\Growing\Desktop\PythonScripts\Telebot Bot.py", line 62, in show_question
self.sender.sendMessage(text=f'Please write a nessessary verbs with dashes: {resultLine}\n')
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\__init__.py", line 513, in sendMessage
return self._api_request('sendMessage', _rectify(p))
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\__init__.py", line 491, in _api_request
return api.request((self._token, method, params, files), **kwargs)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\telepot\api.py", line 154, in request
r = fn(*args, **kwargs) # `fn` must be thread-safe
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\request.py", line 155, in request_encode_body
body, content_type = encode_multipart_formdata(
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\filepost.py", line 78, in encode_multipart_formdata
for field in iter_field_objects(fields):
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\filepost.py", line 42, in iter_field_objects
yield RequestField.from_tuples(*field)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\fields.py", line 182, in from_tuples
content_type = guess_content_type(filename)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\fields.py", line 20, in guess_content_type
return mimetypes.guess_type(filename)[0] or default
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\mimetypes.py", line 309, in guess_type
return _db.guess_type(url, strict)
File "C:\Users\Growing\AppData\Local\Programs\Python\Python310\lib\mimetypes.py", line 122, in guess_type
url = os.fspath(url)
TypeError: expected str, bytes or os.PathLike object, not int
ERROR:root:on_close() called due to TypeError: expected str, bytes or os.PathLike object, not int
I can't get where the mistake is and why I'm getting an error.
Having an issue with the api for Odoo v13. I am able to get the server info but for some reason the uid is not being returned
import xmlrpc.client
url ="localhost:8069"
db = "pnv3"
username = "test"
password = "test"
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
print(common.version())
uid = common.authenticate(db, username, password, url)
print(uid)
getting this error
Traceback (most recent call last):
File "C:/Users/Web Content/.PyCharmCE2019.3/config/scratches/scratch.py", line 11, in <module>
uid = common.authenticate(db, username, password, url)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1452, in __request
verbose=self.__verbose
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1170, in single_request
return self.parse_response(resp)
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1342, in parse_response
return u.close()
File "C:\Users\Web Content\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 656, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 1: 'Traceback (most recent call last):\n File "/odoo/odoo-server/odoo/modules/registry.py", line 59, in __new__\n return cls.registries[db_name]\n File "/odoo/odoo-server/odoo/tools/func.py", line 69, in wrapper\n return func(self, *args, **kwargs)\n File "/odoo/odoo-server/odoo/tools/lru.py", line 44, in __getitem__\n a = self.d[obj].me\nKeyError: \'pnv3\'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File "/odoo/odoo-server/odoo/addons/base/controllers/rpc.py", line 63, in xmlrpc_2\n response = self._xmlrpc(service)\n File "/odoo/odoo-server/odoo/addons/base/controllers/rpc.py", line 43, in _xmlrpc\n result = dispatch_rpc(service, method, params)\n File "/odoo/odoo-server/odoo/http.py", line 138, in dispatch_rpc\n result = dispatch(method, params)\n File "/odoo/odoo-server/odoo/service/common.py", line 61, in dispatch\n return g[exp_method_name](*params)\n File "/odoo/odoo-server/odoo/service/common.py", line 30, in exp_authenticate\n res_users = odoo.registry(db)[\'res.users\']\n File "/odoo/odoo-server/odoo/__init__.py", line 104, in registry\n return modules.registry.Registry(database_name)\n File "/odoo/odoo-server/odoo/modules/registry.py", line 61, in __new__\n return cls.new(db_name)\n File "/odoo/odoo-server/odoo/modules/registry.py", line 73, in new\n registry.init(db_name)\n File "/odoo/odoo-server/odoo/modules/registry.py", line 141, in init\n with closing(self.cursor()) as cr:\n File "/odoo/odoo-server/odoo/modules/registry.py", line 492, in cursor\n return self._db.cursor()\n File "/odoo/odoo-server/odoo/sql_db.py", line 649, in cursor\n return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)\n File "/odoo/odoo-server/odoo/sql_db.py", line 186, in __init__\n self._cnx = pool.borrow(dsn)\n File "/odoo/odoo-server/odoo/sql_db.py", line 532, in _locked\n return fun(self, *args, **kwargs)\n File "/odoo/odoo-server/odoo/sql_db.py", line 600, in borrow\n **connection_info)\n File "/usr/local/lib/python3.7/dist-packages/psycopg2/__init__.py", line 130, in connect\n conn = _connect(dsn, connection_factory=connection_factory, **kwasync)\npsycopg2.OperationalError: FATAL: database "pnv3" does not exist\n\n'>
Process finished with exit cod
1
Databse does exist, have triple checked my password, not sure what else to do at this point.
The url to Odoo server should include protocol part "http://" in the beginning. Strange that you get the version info at all. What do you get as output for the version?
Also you pass the url as the last parameter to authenticate method and this is not required. This should still not give the error you received.
Try your code with these two fixes and report if this helps:
import xmlrpc.client
url ="http://localhost:8069"
db = "pnv3"
username = "test"
password = "test"
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
print(common.version())
uid = common.authenticate(db, username, password, {})
print(uid)
Identical code works on my machine...
I am working with a mobile game API and a Telegram Bot. It worked when I put in a fixed Clantag, but now I wanted to let the user write a tag and add it to the link. The app then should search for the clan and get the right stats. Everything is ok but I get this message now and cannot find my mistake. Would be happy if you could help!
def main():
last_update_id = None
message = ""
while True:
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
message = get_last_update_Message(updates)
clan_stats(updates, message)
def get_last_update_Message(updates):
message = ""
for update in updates["result"]:
message = update["message"]
return message["text"]
def clan_stats(updates, ID):
#https://api.royaleapi.com/clan/1RLU78YU
Link = '"https://api.royaleapi.com/clan/' + ID + '"'
r=requests.get(Link, headers={"Accept":"application/json",
"authorization":"Bearer TOKENHERE"})
clan = r.json()
Full Traceback:
Traceback (most recent call last):
File "/home/Lee63225/clashroyaleclanbot.py", line 188, in <module>
main()
File "/home/Lee63225/clashroyaleclanbot.py", line 184, in main
clan_stats(updates, message)
File "/home/Lee63225/clashroyaleclanbot.py", line 80, in clan_stats
"authorization":"Bearer TOKENHERE"})
File "/usr/lib/python3.7/site-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 503, in request
prep.url, proxies, stream, verify, cert
File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 676, in merge_environment_settings
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
File "/usr/lib/python3.7/site-packages/requests/utils.py", line 760, in get_environ_proxies
if should_bypass_proxies(url, no_proxy=no_proxy):
File "/usr/lib/python3.7/site-packages/requests/utils.py", line 716, in should_bypass_proxies
if is_ipv4_address(parsed.hostname):
File "/usr/lib/python3.7/site-packages/requests/utils.py", line 640, in is_ipv4_address
socket.inet_aton(string_ip)
TypeError: inet_aton() argument 1 must be str, not None
Thank you!
I think it should rather be
Link = 'https://api.royaleapi.com/clan/' + ID
There is some surrounding " in your attempt.
But now as I look, the function is called as clan_stats(update,message). That "message" should be a clantag, make sure it is (as now it comes from get_last_update_Message(), and looks very suspicious.
I have following code which indexes data to elasticsearch using python,
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import requests
from requests.auth import AuthBase
requests.packages.urllib3.disable_warnings()
class TokenAuth(AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['Authorization :Bearer'] = f'{self.token}'
return r
es = Elasticsearch('https://localhost:9200/user/type',ca_certs=False,verify_certs=False,auth=TokenAuth(''))
#requests.get('https://httpbin.org/get', auth=TokenAuth('12345abcde-token'))
res = helpers.bulk(es, "ldif2.json", chunk_size=1, request_timeout=200)
It follows token based autheentication , but whan i run this progam i get below error message ,how do i solve this.
Traceback (most recent call last):
File "bulk_index.py", line 20, in <module>
res = helpers.bulk(es, "ldif2.json", chunk_size=1, request_timeout=200)
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\helpers\actions.py", line 300, in bulk
for ok, item in streaming_bulk(client, actions, *args, **kwargs):
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\helpers\actions.py", line 230, in streaming_bulk
**kwargs
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\helpers\actions.py", line 116, in _process_bulk_chunk
raise e
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\helpers\actions.py", line 112, in _process_bulk_chunk
resp = client.bulk("\n".join(bulk_actions) + "\n", *args, **kwargs)
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\client\utils.py", line 84, in _wrapped
return func(*args, params=params, **kwargs)
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\client\__init__.py", line 1498, in bulk
headers={"content-type": "application/x-ndjson"},
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\transport.py", line 353, in perform_request
timeout=timeout,
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 239, in perform_request
self._raise_error(response.status, raw_data)
File "C:\Users\mkumaru\AppData\Local\Programs\Python\Python37\lib\site-packages\elasticsearch\connection\base.py", line 168, in _raise_error
status_code, error_message, additional_info
elasticsearch.exceptions.AuthenticationException: AuthenticationException(401, 'Access denied')```
I think es should be like this.
es = Elasticsearch("http://127.0.0.1:9200", http_auth=('user', 'passwd'))
I'm not able to pass the user input into JQL query? I've tried no of alternative but nothing works.
Here is the code.
project_name=raw_input("Please give the project name: ")
reporter_name=raw_input("Please provide the name of creator: ")
date_from=raw_input("Please provide the time interval for which you want issues: From ")
date_to=raw_input("Please provide the time interval for which you want issues: To ")"""
total_issues = jira.search_issues('project = %s AND reporter = %s AND created > %s and created < %s' % (projectname, reportername, datefrom, dateto))
print total_issues
It gives me: jira.exceptions.JIRAError
traceback (most recent call last):
File "jiradetailsizmirtomtom.py", line 27, in <module>
for i in jira.search_issues('project = project_name AND reporter = reporter_name AND created > date_from and created < date_to'):
File "/Library/Python/2.7/site-packages/jira/client.py", line 1747, in search_issues
issues = self._fetch_pages(Issue, 'issues', 'search', startAt, maxResults, search_params)
File "/Library/Python/2.7/site-packages/jira/client.py", line 397, in _fetch_pages
resource = self._get_json(request_path, params=page_params, base=base)
File "/Library/Python/2.7/site-packages/jira/client.py", line 2172, in _get_json
r = self._session.get(url, params=params)
File "/Library/Python/2.7/site-packages/jira/resilientsession.py", line 150, in get
return self.__verb('GET', url, **kwargs)
File "/Library/Python/2.7/site-packages/jira/resilientsession.py", line 146, in __verb
raise_on_error(response, verb=verb, **kwargs)
File "/Library/Python/2.7/site-packages/jira/resilientsession.py", line 56, in raise_on_error
r.status_code, error, r.url, request=request, response=r, **kwargs)
jira.exceptions.JIRAError
Can we really pass variable to JQL query? Does JQL allows this?