Search code examples
pythontelegram-bot

telegram bot API 'setMyName' doesn't work


Here is my code

import requests
import json
bot_token = " "  # your bot token
token_url = f"https://api.telegram.org/bot{bot_token}/"

parameters = {
    "name": "sdfjk123",
    "language_code": "en"
}
headers = {
    "Content-Type": "application/json",
}

print(token_url+'setMyName')


def set_name():
    r = requests.post(token_url+'setMyName', json=json.dumps(parameters), headers=headers)
    print(r.json())


set_name()

Here is the error message returned by the request

{'ok': False, 'error_code': 400, 'description': 'Bad Request: BOT_TITLE_INVALID'}

What have I tried

First of all, I checked my token and it has no errors, secondly I tried using request.get(url,params=parameters), which did return success, but the bot name didn't change, so I used the method above. Also, I have used setMyDescription and setMyCommands, which also return success but the bot does not change. It seems that the bot doesn't change when I use the relevant setup parameters, but when I use the query and other parameters, the corresponding information is returned!

Is there any way to fix this?

The problem has been solved

use requests.post(token_url+'setMyName', json=parameters), do not use the json.dumps()!!!


Solution

  • You are passing your data as json=json.dumps(parameters) but you need to use the data param from requests.


    The following code allows me to update the Bot's username

    import requests
    import json
    
    bot_token = "xxx"  # your bot token
    token_url = f"https://api.telegram.org/bot{bot_token}/"
    
    parameters = {
        "name": "FooBar",
        "language_code": ""
    }
    
    def set_name():
        r = requests.post(token_url+'setMyName', data=json.dumps(parameters))
        print(r.json())
    
    set_name()
    

    Response:

    {'ok': True, 'result': True}