Telegram webhook seems not to work with python APIs - webhooks

I'm developing a telegram bot with the help of this API, and I tried to implement it with webhook method, first I tried my bot with getUpdated method and it works like a charm, but when I updated it to webhook, it doesn't seem to work.
I implemented webhook with flask, exactly following this example, except for the ssl certificate and IP, because I have an https domain, so instead of using IP and self signed certificate, I used my domain.
Then I tested my webhook with postman and sent requests with the data I got from api.telegram.org, and again it worked, but when I send a message to my bot in Telegram application, I get no message in the server, seems like telegram does not send the message as it is supposed to.
EDIT: Here I put my code for more clarification
WEBHOOK_HOST = 'mywebsite.com'
WEBHOOK_PORT = '8443'
WEBHOOK_LISTEN = '0.0.0.0'
WEBHOOK_SSL_CERT = "/etc/letsencrypt/live/mywebsite.com/cert.pem"
WEBHOOK_PRIV_CERT = "/etc/letsencrypt/live/mywebsite.com/privkey.pem"
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (TOKEN.get_token())
router = flask.Flask(__name__)
#router.route('/', methods=['GET', 'HEAD'])
def index():
return 'OK'
#router.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
if flask.request.headers.get('content-type') == 'application/json':
json_string = flask.request.json
print json_string["message"]["text"] # here I should get the text of message
return ''
else:
flask.abort(403)
bot.remove_webhook()
time.sleep(3)
bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,certificate=open(WEBHOOK_SSL_CERT, 'r'))
router.run(host=WEBHOOK_LISTEN, port=int(WEBHOOK_PORT), ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_PRIV_CERT), debug=True)

i think you sould use domain name or real IP address.
a little comment from your example link:
In some VPS you may need to put here the IP addr
if you develop on localhost, you can use somesing like ngrok.io

Related

Slack API bot not recognizing bot event subscriptions

I have a slack bot that, for some reason, stopped recognizing certain bot events. I am using the slackeventsapi to import the SlackEventAdapter, and using it to recognize certain bot events, like reaction_added and reaction_removed. Recently that stopped working altogether on my bot, I reset my bot and it still doesn't work. I am unsure as to why.
I have already checked my slack api bot event subscriptions, and I am subscribed to both those events, so I am unsure as to what exactly is causing this to happen. The bot can still post messages to the chat, it just doesn't recognize certain bot events.
Below is an example of some code I am trying to run. the /test works, the reaction_added event never gets called and nothing gets invoked and never prints the payload.
import os
import slack_sdk
from flask import Flask, request, Response
from dotenv import load_dotenv
from pathlib import Path
from slackeventsapi import SlackEventAdapter
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
app = Flask(__name__)
slack_event_adapter = SlackEventAdapter(os.environ['SIGNING_SECRET'],'/slack/events', app)
client = slack_sdk.WebClient(token=os.environ['SLACK_TOKEN'])
#app.route('/test', methods=['POST'])
def test():
print("recognized a test command was sent!")
return Response(), 200
#slack_event_adapter.on("reaction_added")
def reaction(payLoad) -> None:
print(payLoad)
if __name__ == "__main__":
app.run(debug=True, port=8088)
I am running everything on an ngrok server. to better clarify, when I use the /test command on the bot I get a HTTP request POST with return of 200. when I add a reaction to something I do not get an HTTP request, I am unsure as to why.

Replying to a message through a discord bot

I want when I say
$script
to output just any message for now in this below example 'pong'.
I have my token in a separate .env file so I don't need to worry about it
import discord
import os
from discord.ext import commands
intents = discord.Intents.all()
client = discord.Client(intents=discord.Intents.default())
bot = commands.Bot(command_prefix='$', intents=intents)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#bot.command(name="script")
async def getscript(ctx):
await ctx.channel.send("pong")
client.run(os.getenv('TOKEN'))
this is the code below, but upon saying $script, nothing happens the bot is online and it works if I just send a message, but I'm not sure why this isn't working can someone help me out here? I have look at the "do any of these posts answer your question?" section and nothing helps.
Well yes it doesn't work because you're not running it. You have both a Client and a Bot. Your Bot has the $script command, but you're running the Client...
# You have both a Client and a Bot
client = discord.Client(...)
bot = commands.Bot(...)
# The command is registered to the Bot
#bot.command(...)
# You're running the Client
client.run()
Either use a Bot or a Client, but you can't use both. Get rid of your Client and use the Bot for everything instead. commands.Bot is a subclass of discord.Client so it can do everything a Client can do.
There's 0 reason to have both.

Is it possible to capture websocket traffic using selenium and python?

we are using selenium on python and as a part of our automation, we need to capture the messages that a sample website sends and receives after the web page loaded completely.
I have check here and it is stated that what we want to do is achievable using BrowserMobProxy but after testing that, the websocket connection did not work on website and certificate errors were also cumbersome.
In another post here it is stated that, this can be done using loggingPrefs of Chrome but it seemed that we only get the logs up to the time when website loads and not the data after that.
Is it possible to capture websocket traffic using only selenium?
Turned out that it can be done using pyppeteer; In the following code, all the live websocket traffic of a sample website is being captured:
import asyncio
from pyppeteer import launch
async def main():
browser = await launch(
headless=True,
args=['--no-sandbox'],
autoClose=False
)
page = await browser.newPage()
await page.goto('https://www.tradingview.com/symbols/BTCUSD/')
cdp = await page.target.createCDPSession()
await cdp.send('Network.enable')
await cdp.send('Page.enable')
def printResponse(response):
print(response)
cdp.on('Network.webSocketFrameReceived', printResponse) # Calls printResponse when a websocket is received
cdp.on('Network.webSocketFrameSent', printResponse) # Calls printResponse when a websocket is sent
await asyncio.sleep(100)
asyncio.get_event_loop().run_until_complete(main())

How can i have a python flask-socketio script acting as a local server and as a remote client at the same time?

My working setup at the moment:
I have an app which consists of a python flask-socketio server and a react interface. The python server collects some data from a specific connected hardware and sends it through sockets to the react interface.
What i want to add:
Besides the actual functionalities, I also want to add a communication through sockets between the local python server and a remote node server. It is possible for local python server to act as a local server and a remote client?
What i have tried:
I tried to add code for a socketio client on the main script of python server.
here:
from flask_socketio import SocketIO
import socketio
socketio_server = SocketIO(app, async_mode='gevent', engineio_logger=False)
####PART OF THE CODE THAT I TRIED TO ADD THE COMMUNICATION AS A CLIENT###
##Connecting to server as a client
sio = socketio.Client() # !!! at this point i receive a new connection on remote server, however the code freezes on this line and the script hang on until the end of the connection
sio = socketio.Connect(host, port)
#i want to send data to a specific namespace
sio.emit('remote-client', {'foo':'bar'})
########################################################################
# Serve React App
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def serve(path):
if path != "" and os.path.exists("static" + path):
return send_from_directory('static', path)
else:
return send_from_directory('static', 'index.html')
#---------------------Web Sockets-----------------------------#
#socketio_server.on('connect', namespace='/test')
def test_connect():
print 'Client Connected'
#socketio_server.on('disconnect', namespace='/test')
def test_disconnect():
print 'Client disconnected'
if __name__ == '__main__':
print "Starting Server..."
socketio_server.run(app, debug=False)
os.kill(os.getpid(), signal.SIGTERM)
So, is this the right approach to achieve what I want? If it is, how can the python script act as a socketio server and client at the same time?
Regards,
Ricardo
EDIT: I Just realized that I am able to use ordinary sockets (import socket) along with socketio server. But if you have a better approach I will consider!

Connecting Heroku Webhooks with Discord

I am trying to have updates to my heroku app sent to a Discord channel via webhook. However, the delivery attempts fail. I've double checked the Payload URL and it is correct. Not sure how to proceed from here.
Heroku's webhook format is not compatible with Discord so you can't just put a Discord webhook URL into Heroku. You need a middle-man server to receive events from Heroku, and construct and send corresponding messages to Discord.
Found this JS code, should work (change params variable and where it says webhook to your webhook url)
let x = new XMLHttpRequest();
x.open("POST", `<webhook link>`);
x.setRequestHeader('Content-type', 'application/json');
let params = {
username: "Webhook Bot",
content: "<message content as a string>"
}
x.send(JSON.stringify(params));
i should mention that to mention a channel instead of #channel-name you'll have to use <#channelid>, for example <#1234567890> instead of #foo-bar
(this is my first post, sorry if it's a bit bad)
Without being able to see your code and the request structure you are using it will be hard to determine where the issue is coming from exactly, but one thing you might what to check is how you are sending the JSON payload to the Discord webhook URL.
Discord does not seem to accept the request unless you specify that the body of the payload is JSON. I discovered this because of an application I am working on currently. I know this answer is coming significantly after the fact, but it might help someone else down the line!

Resources