I'm trying to automate interaction with a website that uses websockets. In theory all I need to do is get authenticated with steam and then send 1 piece of data, but I'm having trouble getting authenticated.
I manage to get the connection set up. But after I send my steam token (replicating what I see happens in the devtools of my browser), it replies that I am not logged in.
Below is the code I currently have. Locally it doesn't work at all. But on repl.it (an online editor) it has the effect it's supposed to have but the websocket still replies that I am not logged in.
The code:
import asyncio
import websockets
import json
import time
import sys
token = "YOUR_STEAM_TOKEN_HERE"
adress = 'wss://eu.pug.champ.gg/socket.io/?EIO=3&transport=websocket'
authtemplate = '42["authenticate",{{"token":{0}}}]'
rolesupdatetemplate = '42["updateAvailability",{0}]'
async def add(roles):
async with websockets.connect(adress) as websocket:
await websocket.send(authtemplate.format(token))
roles_string = json.dumps(roles)
await websocket.send(rolesupdatetemplate.format(roles_string))
asyncio.get_event_loop().run_until_complete(add({'roles': ['roamer', 'pocket'], 'captain': False})
)
Some extra info:
When on the site normally, the websocket I'm connected to according to the developer tools has an extra argument compared to the one I use in my code. The extra argument being: sid=....
However, adding this manually gives me error code 400.
I've tried looking up how to do this but I can't find the answer anywhere. Do I need to send cookies?
Do I need to get the websocket address in another way rather than manually?
What am I missing?
Related
so im playing a little bit around with my telegram bot, now im already able to send normal messages and pictures. But now i want to be able to send pre recorded voice messages as an answer. In the documentation it says to use send_voice for this matter and it recommends using the file_id of a file thats already on the telegram servers. So thats what i did i send a voice message to the #RawDataBot and he returned to me the file_id of the voice message.
Problem is: When i try to trigger it i get the following error: telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: wrong file identifier/HTTP URL specified
Any ideas here on what i might be doing wrong? Here is the relevant code:
import telebot
API_KEY = <MY_API_KEY>
bot = telebot.TeleBot(API_KEY)
#start
#bot.message_handler(commands=['start'])
def start (message):
bot.send_message(message.chat.id,Textstart)
#bot.message_handler(commands=['pic'])
def start (photo):
bot.send_photo(photo.chat.id, "https://de.wikipedia.org/wiki/Zeus#/media/Datei:Zeus_Otricoli_Pio-Clementino_Inv257.jpg")
#here is the part where he is supposed to send the voice message if someone types in /audio
#bot.message_handler(commands=['audio'])
def start (voice):
bot.send_voice(voice.chat.id,"AwACAgIAAxkBAAEWjl5i5bjyudWAM9IISKWhE1Gjs5ntQgACLx8AApcNKEv97pVasPhBoCkE",)
bot.polling()
There are multiple reasons, but I think it is because of these:
file_id is unique for each individual bot and can't be transferred from one bot to another.
file_id uniquely identifies a file, but a file can have different valid file_ids even for the same bot.
See here.
I am working on code to login to my app using Microsoft login using fastapi. I am able to call microsoft login page and after entering the login credentials i am getting the error "{"detail":"'state' parameter in callback request does not match our internal 'state', someone may be trying to do something bad."}"
**main.py**
from fastapi_sso.sso.microsoft import MicrosoftSSO
app1 = FastAPI()
microsoft_sso = MicrosoftSSO("client-id", "client-secret", "http://localhost:8000/dashboard")
#app1.get("/microsoft/login")
async def microsoft_login():
return await microsoft_sso.get_login_redirect()
#app1.get("/dashboard")
async def microsoft_callback(request: Request):
user_new = await microsoft_sso.verify_and_process(request) #getting error at this point
print(user_new.id)
print("Hello Microsoftttttttttttttttt")
I had the same problem with this SOO using the google one. The solution was to create a new pair of keys and use one when developing the platform locally and the other one being used only in production. After doing this, the issue faded away. Just like that.
You probably need to pass use_state=False in the SSO constructor:
microsoft_sso = MicrosoftSSO("client-id", "client-secret", "http://localhost:8000/dashboard", use_state=False)
If the application is distributed (i.e multiple web servers), or if it plans to handle multiple simultaneous SSO flows (i.e login request for user A, then login request for user B, then callback for A then callback for B), then the default use_state=True is a bad idea. No idea how much more secure is it, but the above reasons are enough for me to disable this "feature".
What it does is, when generating the redirect url it generates a state, stores it locally and passes it as a cookie to provider, then in callback it checks if the cookie matches local state.
Hi I have a program in python that generates results every one hour. The result can be of anything.This program will run in local machine or in the virtual private network.
I have two requirements
1. Send this python generated result to one telegram group [Group name "ourworld"](created by me) automatically without user intervention . (I have desktop telegram client running or web.telegram.org running in the same system)
Send this result to gmail group email ID.
what are the methods available to achieve this requirement .Is there any working code available to do this job .Please share the info and details.
Edit:
The Issue that i am facing :
1.created a Bot using BotFather.
2.Adding this Bot to my Group ,Here i get an error could not add an member So added the Bot as admin in the group
3.Token of the BOT noted down.
4. Trying to get ChatId
in this forum (https://web.telegram.org/#/im?p=g154513121) someone says number after p=g is the chartid ,In my case there is no
number it shows #testingname like this.
Using this approach trying to get the Chat ID https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/getme
so here 738909732 become a chat Id (in this case why we need seperate
call for the chart id)
here it is true as response coming! Here the chat id is the ID of the my "testingname" no chart id generated for the group.
6.Now packing the URL to see the response i am getting this error.
https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/sendMessage?chat_id=738909732&text=testing
the output if i run this in browser
{"ok":false,"error_code":400,"description":"Bad Request: chat not
found"} {"ok":false,"error_code":403,"description":"Forbidden: bot
can't send messages to bots"}
How to resolve this issue and make the BOT working .why i am not able to add BOT to my group that says error "Cant Add user"
How to make this telegram group working.
Note : Using BotFather BOT created
In case for sending message to telegram group the above method provided by bipin_s works where the chat_id = -xxxxxx is used.This is correct id followed by - symbol to be used.
For Posting message in the "telegram channel " a minor change needs to be done in the URL.The URL must be framed as below .
url = "https://api.telegram.org/botTokenID/sendMessage?chat_id=#yourChannelChatID&text=message"
Replace the TokenID with your BOT tokenID replace the yourChannelChatID with your channel chart id.Please note that the channel id is not negative id.
the code will look like this
import request
url = "https://api.telegram.org/botXyz:wwwwDFSJSJSAX/sendMessage?chat_id=#telechanneltesting&text=message"
requests.post(url)
Here the "message" as in the URL it will be posted in telegram channel.
How to get channel id ?
Go to https://web.telegram.org/#/im in browser ,after login now search your "channel".Now in the browser address bar you will one link like https://web.telegram.org/#/im?p=#llliopppppsssssr
p=#llliopppppsssssr after the equal symbol what comes is channel chat ID.
to send message to the telegram "group" without any user intervention , you require a telegram bot. create one using telegram bot-father. take a look at this link. also note the token while creating the bot. This method will work only for telegram Group .Telegram channel another method to be followed which MarxBabu answered below in his answers post.
import requests
# telegram url
url = "https://api.telegram.org/bot<Token>"
def send_mess(text):
params = {'chat_id':-xxxxxxx, 'text': text}
response = requests.post(url + 'sendMessage', data=params)
return response
send_mess(result_you_want_to_send)
to get the chat_id follow the steps mentioned here. note: group chat id's always starts with '-' . e.g. of group chat_id -356163873. A token and chat_id is only what you require to send message to telegram group.
for sending group emails you have to search more as i do not know much
I have it running on a Raspberry pi. You must look for botfather to get your telegram token.
import telepot
from telepot.loop import MessageLoop
telegram_token = 'xxxx:xxxxxx'
user = 4444444
bot = telepot.Bot(telegram_token)
bot.sendMessage(user, 'Hey!')
For configuring gmail I don't have something here right now...
You can send emails in python through SMTP or using the Mailgun Api
I personally prefer using Mailgun as it is easier to setup and sending an email is as easy as sending a post request to mailgun.
You can get the free version of the api and add your group email id to the sandbox (to avoid spam) and then use requests to post an email with the given api token
I have the following scenario I would like to implement:
User surfs to our website
User enters a bitcoin address.
A websocket is created to the server, passing the address.
The server registers a callback with Blocktrail
When the callback is triggered (a payment was seen by Blocktrail) we send a message back to the browser.
The page the user is browsing is updated to show the message recieved
I'm using webhooks from the Blocktrail API to "listen" to an event, being the reception of coins on an address.
Now, when the event happens, the API does a POST to my URL. This should send a message to the browser that is connected to my server with socket.io (such as 'payment seen on blockchain')
So the question is,
How can I send a message from a route to a socket using flask-socketio
Pseudo code:
#app.route('/callback/<address>')
def callback(id):
socketio.send('payment seen on blockchain')
#socketio.on('address',address)
def socketlisten(address):
registerCallback(address)
I'm going to describe how to solve this using Flask-SocketIO beta version 1.0b1. You can also do this with the 0.6 release, but it is a bit more complicated, the 1.0 release makes addressing individual clients easier.
Each client of a socket connection gets assigned a session id that uniquely identifies it, the so called sid. Within a socket function handler, you can access it as request.sid. Also, upon connection, each client is assigned to a private room, named with the session id.
I assume the metadata that you receive with the callback allows you to identify the user. What you need is to obtain the sid of that user. Once you have it, you can send your alert to the corresponding room.
Example (with some hand-waving regarding how you attach a sid to an address):
#app.route('/callback/<address>')
def callback(address):
sid = get_sid_from_address(address)
socketio.send('payment seen on blockchain', room=sid)
#socketio.on('address')
def socketlisten(address):
associate_address_with_sid(address, request.sid)
I am researching what it would take to make a web app that would interact with e-mails directly. Like you would send to something#myapp.com and the app would tear it apart and determine who it's from, if they are in the DB, what is the subject line, etc.
I am working with/most familiar with python and flask.
Could anyone get me started in the right direction of how to get an e-mail to interface with my flask app code?
There are several approach you can take:
write some code which uses IMAP or POP to retrieve emails and process them. Either run this from a crontab (or something similar) or add it to your flask app and trigger it in there, either through a crontab that requests a magic URL or setting up a custom timer thread.
configure your MTA to deliver email for something#myapp.com by feeding it to a program you write (for example in Exim you could use a pipe transport) . In that program you can either process it directly, or do something like POSTing it to your flask app.
I've done something along these lines recently, with a simple bookmarking web-app. I have the usual bookmarklet way of bookmarking something to it, but I also wanted to be able to e-mail links to it from apps like Reeder on my iPhone and whatever. You can see what I ended up with on GitHub: subMarks.
I use Google Apps for your Domain for my email, so I created a special address for my app to look at - I really didn't want to try building/configuring my own e-mail server.
the mail_daemon.py file from above is run as a cron job every 5 minutes. It connects to the email server using the poplib Python package, processes the emails that are there and then disconnects (one part I feel compelled to point out is that I check that the emails are from me before they are processed :) )
My Flask app then provides the front end to the bookmarks, displaying them from the database.
I decided not to put the email handling code into the actual flask app, because it can be rather slow and would only run when the page was visited, but you could do this if you wanted.
Here's some barebones code to get things going:
import poplib
from email import parser
from email.header import decode_header
import os
import sys
pop_conn = poplib.POP3_SSL('pop.example.com')
pop_conn.user('my-app#example.com')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message into an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
# check message is from a safe recipient
if 'me#example.com' in message['from']:
# Get the message body text
if message['Content-Type'][:4] == 'text':
text = message.get_payload() #plain text messages only have one payload
else:
text = message.get_payload()[0].get_payload() #HTML messages have more payloads
# decode the subject (odd symbols cause it to be encoded sometimes)
subject = decode_header(message['subject'])[0]
if subject[1]:
bookmark_title = subject[0].decode(subject[1]).encode('ascii', 'ignore') # icky
else:
bookmark_title = subject[0]
# in my system, you can use google's address+tag#gmail.com feature to specifiy
# where something goes, a useful feature.
project = message['to'].split('#')[0].split('+')
### Do something here with the message ###
pop_conn.quit()