Skip to content

Instantly share code, notes, and snippets.

@VycktorStark
Last active June 29, 2020 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VycktorStark/578af80b406d259aa22de40319ff9f5a to your computer and use it in GitHub Desktop.
Save VycktorStark/578af80b406d259aa22de40319ff9f5a to your computer and use it in GitHub Desktop.
An example of a function created to analyze whether the defined ID left the chat blocked for the bot; if true, the bot will inform the administrator
__author__ = "Vycktor Stark"
"""
This function was created to analyze if the defined ID left the chat blocked for the bot;
if true, the bot will inform the administrator
"""
def checkchat(method="sendMessage", **args):
import requests, os
"""
This information below is not necessary for this function to work,
the information can be loaded in another way,
just edit the code below to adapt
"""
chatadmin=438131290 #Defining ID of admin
token = os.environ['SECRET_KEY'] # Defining bot token
apitelegram = f"https://api.telegram.org/bot{token}" # Defining api of telegram
# The information below can be edited as long as you know what you are doing
data = requests.post(f"{apitelegram}/{method}", params=locals()['args'], headers={'content-type': 'application/json', 'Cache-Control': 'no-cache'})
if (data.status_code == 200):
pass
elif (data.status_code == 403) and (data.json()['description'] == 'Forbidden: bot was blocked by the user'):
arg = locals()['args']
if ("text" in arg):
arg['text'] = f"An error has occurred\nDescription: {data.json()['description']}\nID user: {arg['chat_id']}"
elif ("caption" in arg):
arg['caption'] = f"An error has occurred\nDescription: {data.json()['description']}\nID user: {arg['chat_id']}"
arg['chat_id'] = chatadmin
data = requests.post(f"{apitelegram}/{method}", params=arg, headers={'content-type': 'application/json', 'Cache-Control': 'no-cache'})
else:
print(f"Error Code:{data.status_code}\nDescription: {data.json()['description']}")
# Example of how to call the function:
checkchat(chat_id=884431779, text='ping')
checkchat(chat_id=884431779, text='<b>ping</b>', parse_mode='HTML')
"""
Note: This function works with the same parameters
as the https://core.telegram.org/bots/api#sendmessage api,
but you can also use another parameter of the same api,
for example: https://core.telegram.org/bots/api#sendphoto just run it as follows:
checkchat(method="sendPhoto", chat_id=884431779, photo="https://img.olhardigital.com.br/uploads/acervo_imagens/2020/04/r4x3/20200423030657_660_495_-_python.jpg", caption='<b>ping</b>', parse_mode='HTML')
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment