How to convert tdata to telethon session? - python

I need to convert telegram data to telethon session.
How can i do this?
I tried to find a solution, spent three days, but I didn’t find anything

It's been nearly two years, but there's now a Python library called opentele created to do this.
Assuming you already have Python knowledge, please follow the steps below.
First you need to install opentele from PyPi:
pip install opentele
Preparing:
You need to have a tdata folder that is already authorized (have at least one logged-in account).
The default path to tdata folder on Windows is located at %appdata%\Telegram Desktop\tdata.
Create a python (.py) file and import these things:
from opentele.td import TDesktop
from opentele.tl import TelegramClient
from opentele.api import API, UseCurrentSession, CreateNewSession
import asyncio
And you also need to put the main code inside an async function:
async def main():
# PUT EXAMPLE CODE HERE
asyncio.run(main())
Initialize TDesktop from tdata folder
Load the tdata folder into a TDesktop object:
# Load TDesktop client from tdata folder
tdataFolder = r"C:\Users\<username>\AppData\Roaming\Telegram Desktop\tdata"
tdesk = TDesktop(tdataFolder)
# Check if we have loaded any accounts
assert tdesk.isLoaded()
Converting TDesktop to TelegramClient
There are two ways you can do this, either by using the current session or creating (login to) a new session.
Use the current session:
# flag=UseCurrentSession
#
# Convert TDesktop to Telethon using the current session.
client = await tdesk.ToTelethon(session="telethon.session", flag=UseCurrentSession)
Create a new session:
# flag=CreateNewSession
#
# Convert TDesktop to Telethon by creating a new session.
# CreateNewSession will use the current session (in tdata folder) to authorize a new session using QR Login.
# If 2FA is enabled for this account, you must specify the password via the password argument.
# This is of course slower than UseCurrentSession.
client = await tdesk.ToTelethon(session="telethon.session", flag=CreateNewSession)
Connect and print all logged-in sessions.
# Connect and print all logged-in sessions of this client.
# Telethon will save the session to telethon.session on creation.
await client.connect()
await client.PrintSessions()
Final result example
from opentele.td import TDesktop
from opentele.tl import TelegramClient
from opentele.api import API, UseCurrentSession
import asyncio
async def main():
# Load TDesktop client from tdata folder
tdataFolder = r"C:\Users\<username>\AppData\Roaming\Telegram Desktop\tdata"
tdesk = TDesktop(tdataFolder)
# Check if we have loaded any accounts
assert tdesk.isLoaded()
# flag=UseCurrentSession
#
# Convert TDesktop to Telethon using the current session.
client = await tdesk.ToTelethon(session="telethon.session", flag=UseCurrentSession)
# Connect and print all logged-in sessions of this client.
# Telethon will save the session to telethon.session on creation.
await client.connect()
await client.PrintSessions()
asyncio.run(main())
The result
The session will be saved to telethon.session file.
You can use this telethon.session with telethon, or use it directly with opentele - which is recommended because you don't need your own API_ID and API_HASH, the library by default will use Official Telegram API.
Remark
opentele is a very well documented library, you can find its documentation here.
It can also convert telethon sessions back to tdata and it's usable with Telegram Desktop.
Warning
According to its docs, you must continue using the associated API which you've had used to create that session whenever connecting to the server, or else you're at risk of losing that account.

Related

How to download incoming image marked as spoiler with telethon?

I'm trying to create a client able to forward and store all the media sent to him via telegram. Everything works fine with all media types, the problem occurs when the client receives a media marked as spoiler. The media is usually stored in the event.media attribute, but when this happens the media type is MessageMediaUnsupported, so there is no way to extract the actual media file. I'm running version 1.26.1 of telethon, and the author told me I should be able to do what i want. What am I missing?
This is the code I'm using:
from telethon import TelegramClient
async def newMessageHandler(client,event):
print(type(event.media)) #this prints "MessageMediaUnsupported" when receiving a spoiler media
client=TelegramClient("username","api_id","api_hash")
client.start(phone="phone_number")
#client.on(events.NewMessage())
async def handler(event):
asyncio.create_task(newMessageHandler(client,event))
asyncio.get_event_loop().run_forever()

how to run a python code with impersonated Service Account

i am coming here after searching google but i am not able to find any answer which i can understand. Kindly help me with my query.
If i want to access GCP resource using an impersonated service account i know i can use it using commands like for example to list a bucket in a project:
gsutil -i service-account-id ls -p project-id
But how can i run a python code ex: test1.py to access the resources using impersonate service account ?
Is there any package or class that i need to use it ? if yes then how to use ? PFB the scenario and code:
I have a pub/sub topic hosted in project-A, where owner is xyz#gmail.com and I have a python code hosted in project-B where owner is abc#gmail.com.
In project-A I have created a service account where I have added abc#gmail.com to impersonate the service account which has pub/sub admin role. Now how can I access pubsub topic via my python code in project-B without using the keys ?
"""Publishes multiple messages to a Pub/Sub topic with an error handler."""
import os
from collections.abc import Callable
from concurrent import futures
from google.cloud import pubsub_v1
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "C:\gcp_poc\key\my-GCP-project.JSON"
project_id = "my-project-id"
topic_id = "myTopic1"
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)
publish_futures = []
def get_callback(publish_future: pubsub_v1.publisher.futures.Future, data: str) -> Callable[[pubsub_v1.publisher.futures.Future], None]:
def callback(publish_future: pubsub_v1.publisher.futures.Future) -> None:
try:
# Wait 60 seconds for the publish call to succeed.
print(f"Printing the publish future result here: {publish_future.result(timeout=60)}")
except futures.TimeoutError:
print(f"Publishing {data} timed out.")
return callback
for i in range(4):
data = str(i)
# When you publish a message, the client returns a future.
publish_future = publisher.publish(topic_path, data.encode("utf-8"))
# Non-blocking. Publish failures are handled in the callback function.
publish_future.add_done_callback(get_callback(publish_future, data))
publish_futures.append(publish_future)
# Wait for all the publish futures to resolve before exiting.
futures.wait(publish_futures, return_when=futures.ALL_COMPLETED)
print(f"Published messages with error handler to {topic_path}.")
Create a Service Account with the appropriate role. Then create a Service Account key file and download it. Then put the path of the key file in the "GOOGLE_APPLICATION_CREDENTIALS" environment variable. The Client Library will pick that key file and use it for further authentication/authorization. Please read this official doc to know more about how Application Default Credentials work.

Slack API Events are not registering in our application

Hello Fellow Slack Bot Enthusiasts.
It's my first time to start setting up a Slack Bot (and I don't have a lot of dev experience, so I wanted to inquire!) .
For this, I used python and Slack bolt.
Background
I was trying to setup my Amazon EC2 Web Instance's Load Balancer to accept slack events from my Workspace. In the below photo, I am now able to have my Endpoint URL Verified in the Slack bot.
Next, I am trying to follow the instructions listed in the Slack Bolt homepage that told me to create the app.py test file. So I followed through on the instructions and ensured that I subscribed to below events:
app_home_opened
message.channels
message.groups
message.im
Then I created the sample app.py file from the article, that was supposed to handle the app_home_opened event.
Now I tried to run the application in my command line (I added the section for #app.event(app_home_opened), and all the other required events ), and I tried to trigger the app_home_opened, message.channels, message.im events, by opening the home page of my bot and by dm-ing the bot and inviting it to a channel and trying to talk to it - but I don't seem to be receiving any payload in the back-end.
I wanted to inquire about the "Verified" notification from the Slack Bot. Does this ensure that the connection between my chatbot code and the server are actually linked?
In addition, I wanted to inquire about ways to test this so that I can ensure that the connection is actually working as expected.
If you could share some thoughts about what I can do to test the communication, it would be much appreciated. Thank you!
Summary
TLDR:
Problem: My chatbot is not receiving any payload from Slack.
Expected: I think there should be some interaction saying HTTP / 200 response to indicate that it is OK, etc.
Actual: The chatbot just remains the same saying "⚡Bolt App is Running"
What I've tried:
Reinstalling the application to ensure that all my changes were saved and were reflected properly in my Slack Environment
Testing the communication by curling through to the URL (it responded with challenge parameter), so I thought that it was OK
Testing the communication by entering some text via DM / channel communication, and opening the homepage.
Sample Code:
import os
# Use the package we installed
from slack_bolt import App
# Initializes your app with your bot token and signing secret
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
# Add functionality here
# #app.event("app_home_opened") ...
# added some of the code from the guide here and the other #app.events ("")
# Start your app
if __name__ == "__main__":
app.start(port=int(os.environ.get("PORT", 3000)))
slack_bolt, for some reason that escapes me, does not seem to create the event handler endpoint (/slack/events) and instead seems to prefer running the application in socket mode. It may still be worth looking into socket mode (see SocketModeHandler) but this example from slack_bolt's github repo ended up getting me to my solution: https://github.com/slackapi/bolt-python/blob/main/examples/flask/app.py
The short-ish version is you have to utilize slack_bolts's flask adapter to create a SlackRequestHandler then create a flask app, define the slack events endpoint (/slack/events) for the flask app, and pass the result to the bolt SlackRequestHandler (Events Endpoint -> Flask -> SlackRequestHandler -> Bolt):
import os
from flask import Flask, request
from slack_bolt import App
from slack_bolt.adapter.flask import SlackRequestHandler
bolt_app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)
flask_app = Flask(__name__)
handler = SlackRequestHandler(bolt_app)
# Add functionality here
# #bolt_app.event("app_home_opened") ...
# added some of the code from the guide here and the other #bolt_app.events ("")
#flask_app.route("/slack/events", methods=["POST"])
def slack_events():
return handler.handle(request)
if __name__ == "__main__":
flask_app.run()
Hope this helps, cheers!

Why can't I grant authorization to my Spotify app?

I am using the spotipy library to add songs to a playlists but I keep getting errors when trying to use the 'playlist-modify-private' scope. When trying to gain authorization, the web browser opens and I allow the app access to my spotify accoutn and then i'm immediately met with an error screen. Rerunning the app just brings me straight to the error screen. I get no error code or anything so I'm lost as to why this is happening.
self.scope = 'playlist-modify-private'
self.redirect_uri = 'localhost:8888/callback'
self.auth = util.prompt_for_user_token(username=self.username,
scope=self.scope,
client_id=self.client_id,
client_secret=self.client_secret,
redirect_uri=self.redirect_uri)
I saw a post saying that for this scope i should be using util module for auth but i've had no luck. Originally I was using the auth SpotifyClientCredentials object and was able to finish most of the project but I was unable to modify playlist since it doesn't take a scope. I'm at a loss if anyone can provide any input.
Try this:
First set the following environment variables on your env.
SPOTIPY_CLIENT_ID="<your_client_id>"
SPOTIPY_CLIENT_SECRET="<your_client_secret>"
SPOTIPY_REDIRECT_URI="http://127.0.0.1:8888/callback"
SPOTIPY_CLIENT_USERNAME="<your_username>"
And then run the following (I'm using dotenv to load the variables above) Check out the doc here:
import os
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from dotenv import load_dotenv
load_dotenv() # Load your environment variables from a .env file
spotify_user = os.environ.get("SPOTIPY_CLIENT_USERNAME")
spotify_scope = "playlist-modify-private"
oauth = SpotifyOAuth(username=spotify_user, scope=spotify_scope)
user_token = oauth.get_access_token(as_dict=False)
That will take you to your redirect_uri and generate a .cache-<your_username> file with all the information needed (token, refresh_token, etc.)
Then you create your spotify client with:
spotify = spotipy.Spotify(auth=user_token)
This will automatically get your token or get a refresh token in case it's needed so you won't have to worry about this.
And then you will be able to modify your playlist with:
spotify.user_playlist_add_tracks(
user=os.environ.get("SPOTIPY_CLIENT_USERNAME"),
playlist_id="<your_playlist_uri>",
tracks=["<track_uri>"])
Here's the doc reference for the environment variables used by the spotipy library: https://spotipy.readthedocs.io/en/2.15.0/?highlight=environment%20variables#quick-start

How to use python-slackclient RTM using multiple token (bot-user)

Hi I have an issue integrating slack custom bot-user into my slack app, based on python-slackclient documentation python-slackclient
to use the RTM
import time
from slackclient import SlackClient
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
sc = SlackClient(token)
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"
that code is working for bot-user token, but since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
any solution or example how to do it?
Cheers,
Your question is had to understand. You wrote:
since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
The access token you're using here...
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
...should be the same as the access token that is associated with your bot. (You should not make your bot use your own personal access token!) You can get an access token for your bot at https://my.slack.com/services/new/bot (assuming you're logged into Slack in the browser with which you follow that link).
If you participate in multiple Slack "teams" (a Slack "team" being basically a company), you'll need to set up a separate bot for each "team". Each bot will have a different access token. To pass the correct access token in to your bot, you could add a command-line parameter, or read the token from an environment variable, or read it from disk, among other options.
You can loop over tokens for connecting if you are planning to setup bot
for multiple teams, then your code can be converted to :-
clients = [SlackClient(token) for t in tokens]
for client in clients:
client.rtm_connect()
while True:
for client in clients:
print client.rtm_read()
time.sleep(1)

Categories