Getting Telegram Error after Updating to new Environment

photo_2023-05-31_20-37-09

Successfully Resolved the flask errors with the help of friends here but when I try to send a message using the webhook I’m getting this error now… if anyone can help me to resolve this will be more helpful… Thank you

Welcome to the community @GSV-GROUPGROUP

Can you please send us the link to your repl so we can check it out?

1 Like

https://replit.com/@GSV-GROUPGROUP/SharksPremiumKLSE?v=1

Right, I will solve asap

1 Like

I am not good at python but here we go

import os
import json
from telegram import Bot

def sendMessage(data):
    tg_bot = Bot(token=os.environ['TOKEN'])
    channel = os.environ['CHANNEL']
    try:
        print('--->Sending message to telegram')
        serialized_data = json.dumps(data)  # serialize data to JSON
        tg_bot.sendMessage(
            channel,
            serialized_data,  # pass serialized data to sendMessage function
            parse_mode="MARKDOWN",
        )
        return True
    except KeyError:
        print('--->Key error - sending error to telegram')
        tg_bot.sendMessage(
            channel,
            serialized_data,  # pass serialized data to sendMessage function
            parse_mode="MARKDOWN",
        )
    except Exception as e:
        print("[X] Telegram Error:\n>", e)
    return False

try this on ur telegram.py

1 Like

Sorry if this does not work.
I’m not very good at python im trash at it lolz.
just pray. :pray:

Moment of truth, does it work for you? I will try my best to resolve this for u.
hell nah its a no i can tell.
If it does not work, send ss of error.

Thanks a lot but still am getting the same error

try this:

import os
import json
from telegram import Bot

def sendMessage(data):
    tg_bot = Bot(token=os.environ['TOKEN'])
    channel = os.environ['CHANNEL']
    try:
        # Check if data is JSON serializable
        json.dumps(data)
    except TypeError:
        print("[X] Unable to serialize data to JSON:\n>", data)
        return False
    else:
        # Serialize data to JSON
        serialized_data = json.dumps(data)
    try:
        print('--->Sending message to telegram')
        tg_bot.sendMessage(
            channel,
            serialized_data,
            parse_mode="MARKDOWN",
        )
        return True
    except KeyError:
        print('--->Key error - sending error to telegram')
        tg_bot.sendMessage(
            channel,
            serialized_data,
            parse_mode="MARKDOWN",
        )
    except Exception as e:
        print("[X] Telegram Error:\n>", e)
    return False

does it work?
@GSV-GROUPGROUP
does a heart mean yes?

1 Like

Testing now… will update the screenshot

unable to serialize data to JSON

Wait. Do you know where the error comes from?

Sorry, I’m not sure… Not really into coding

Before updating the new environment it was working fine because i just fork the repl the link someone shared to create webhook … I really do not have any idea how to resolve this after updating to new environment

  1. Add a print statement that logs the content and type of payload before sending a message to Telegram:
print(payload)
print(type(payload))

then next i need to test

After posting the message to Telegram, add a print statement that logs the message id of the message sent to Telegram:
msg = tg_bot.sendMessage(
        channel,
        payload,
        parse_mode="MARKDOWN",
    )
print(msg.message_id)

let me know what you get.

can you please explain where to paste the exact code

from lines 9 to 36, replace it with

@app.route('/webhook', methods=['POST', 'GET'])
def post_message():
  try:
    jsonRequest=request.args.get("jsonRequest")
    chart = request.args.get("chart")
    tblfmt = request.args.get("tblfmt", default = 'plain')
    loginRequired = request.args.get('loginRequired', default=False, type=lambda v: v.lower() == 'true')
    print("[I] Login Required : ",loginRequired)
    print("[I] Chart : ",chart)
    if request.method == 'POST':
      payload = request.data
      # Add print statements here
      print(payload)
      print(type(payload))
      if jsonRequest == "true":
        jsonPayload = request.json
        if 'Custom' in jsonPayload:
          chart = jsonPayload.pop('Custom')
        dataframe = pd.DataFrame(jsonPayload, index=[0]).transpose()
        payload = '```'+tabulate(dataframe,tablefmt=tblfmt)+'```'
      print("[I] Payload: \n", payload)
      telegrambot.sendMessage(payload)
      if chart != None:
        captureutil.send_chart_async(chart, loginRequired)
      return 'success', 200
    else:
      print("Get request")
      return 'success', 200
  except Exception as e:
    print("[X] Exception Occured : ", e)
    return 'failure', 500

at line 39

place this in

msg = tg_bot.sendMessage(
        channel,
        payload,
        parse_mode="MARKDOWN",
    )
print(msg.message_id)

then let me know what you get.

after changing 9 to 36 it’s showing like this…when i try to send message also no response / error codes

from flask import Flask, request
from threading import Thread
import telegrambot
import captureutil
import pandas as pd
from tabulate import tabulate

app = Flask('')
@app.route('/webhook', methods=['POST', 'GET'])
def post_message():
  try:
    jsonRequest=request.args.get("jsonRequest")
    chart = request.args.get("chart")
    tblfmt = request.args.get("tblfmt", default = 'plain')
    loginRequired = request.args.get('loginRequired', default=False, type=lambda v: v.lower() == 'true')
    print("[I] Login Required : ",loginRequired)
    print("[I] Chart : ",chart)
    if request.method == 'POST':
      payload = request.data
      # Add print statements here
      print(payload)
      print(type(payload))
      if jsonRequest == "true":
        jsonPayload = request.json
        if 'Custom' in jsonPayload:
          chart = jsonPayload.pop('Custom')
        dataframe = pd.DataFrame(jsonPayload, index=[0]).transpose()
        payload = '```'+tabulate(dataframe,tablefmt=tblfmt)+'```'
      print("[I] Payload: \n", payload)
      telegrambot.sendMessage(payload)
      if chart != None:
        captureutil.send_chart_async(chart, loginRequired)
      return 'success', 200
    else:
      print("Get request")
      return 'success', 200
  except Exception as e:
    print("[X] Exception Occured : ", e)
    return 'failure', 500

@app.route('/')
def main():
  return 'Your bot is alive!'

def run():
  app.run(host='0.0.0.0', port=5000)


def start_server_async():
  server = Thread(target=run)
  server.start()

def start_server():
  app.run(host='0.0.0.0', port=5000)