I am using telethon to automate some tasks on Telegram.
I am trying to create an API where third party users can provide phone number and enter code through an api. I have got the phone number part working, As I allow users to input their phone number through a webservice, this gets wrote to a file, then I am opening that file and fetching the phone number in python which is {number}, I then connect to the client using below.
client = TelegramClient(f'{number}', API_ID, API_KEY)
try:
await client.connect()
except Exception as e:
print('Failed to connect', e, file=sys.stderr)
return
Once the code is run the user enters the verification code (not in the python app) which gets wrote to a file.
And in python the following is returned
Please enter the code you received:
I can open the file which contains the verification code which as {code}
but how do I use {code} to reply to 'Please enter the code you received:'
Thanks
I think that you get the code on telegram and not in the file
It is possible, but this will be very complex as the code is sent to another device. You can write custom Telegram client that will send this code to your program, but it is too complex and in 99.9% of cases you won't need it.
Edit:
If you already have this code, let's say in code variable, you can try to use method sign_in() instead of connect()
try:
await client.sign_in(number, code)
except Exception as e:
print('Failed to connect', e, file=sys.stderr)
return
Reference for sign_in() in docs
Related
I want to write a simple slack bot, which responds a given string to # mentions, however I am not able to make the official documentation code to work.
I gave all OAuth permission to the bot and have the following code:
from slack import RTMClient
#RTMClient.run_on(event="message")
def gravity_bot(**payload):
data = payload['data']
print(data.get('text'))
try:
rtm_client = RTMClient(
token="my_token_auth_code",
connect_method='rtm.start'
)
print("Bot is up and running!")
rtm_client.start()
except Exception as err:
print(err)
I think the connection is established, as the "Bot is up and running" message appears, however on the slack channel to bot seems to be offline, also I am not able to get any response in the terminal, not for direct messages, not for channel messages even after inviting the bot to given channels.
Sorry couldn't let this one go.. I figured it out and here are the steps:
Create a "Classic" app in Slack (this is the only way to get the appropriate scopes), just click this link: https://api.slack.com/apps?new_classic_app=1
From the "Add features and functionality" tab click on "bots":
Click the "Add Legacy Bot User" button (this will add the "rtm.stream" scope that you need, but that you cannot add manually)
From the basic information page, install your app in a workspace
From the OAuth & Permissions page, copy the "Bot User OAuth Access Token" (the bottom one)
Run the following code (slightly modified version of the code in the docs)
from slack_sdk.rtm import RTMClient
# This event runs when the connection is established and shows some connection info
#RTMClient.run_on(event="open")
def show_start(**payload):
print(payload)
#RTMClient.run_on(event="message")
def say_hello(**payload):
print(payload)
data = payload['data']
web_client = payload['web_client']
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
web_client.chat_postMessage(
channel=channel_id,
text=f"Hi <#{user}>!",
thread_ts=thread_ts
)
if __name__ == "__main__":
slack_token = "<YOUR TOKEN HERE>"
rtm_client = RTMClient(token=slack_token)
rtm_client.start()
Previous answer:
Hmm, this is tricky one... According to the docs this only works for "classic" Slack apps, so that might be the first pointer. It explicitly says that you should not upgrade your app. Furthermore, you'll need to set the right permissions (god knows which ones) by selecting the "bot" scope.
Honestly, I haven't been able to get this running. Looks like Slack is getting rid of this connection method, so you might have more luck looking into the "Events API". I know it's not the ideal solution because its not as real-time, but it looks better documented and it will stay around for a while. Another approach could be polling. Its not sexy but it works...
My guess is that your problem is that there is not a valid connection, but there is no proper error handling in the Slack library. The message is printed before you actually connect, so that doesn't indicate anything.
I am trying to send messages to Facebook friends via Messenger. I found a tutorial & tried it.
import fbchat
from getpass import getpass
username = str(raw_input("Username: "))
client = fbchat.Client(username, getpass())
no_of_friends = int(raw_input("Number of friends: "))
for i in xrange(no_of_friends):
name = str(raw_input("Name: "))
friends = client.getUsers(name) # return a list of names
friend = friends[0]
msg = str(raw_input("Message: "))
sent = client.send(friend.uid, msg)
if sent:
print("Message sent successfully!")
When I ran the program, it requested me my password. And, of course, I entered it. But Facebook doesn't accept the request from my program & lock my Facebook account. I think this is due to security reasons. Then how can I log in to my Facebook from python program without getting locked? Thanks.
This seems like the issue lies with your library, not with you. You should make a new issue at their github page. https://github.com/carpedm20/fbchat
You can selenium to remotely control the browser and do stuff a normal user can do, including logging into facebook.
I'm playing around with making an auto reply bot that scanns r/All submission comments for a given command eg. !command
When it detects this command it replies to the comment with a string:
eg. "Hello"
The error I get is that there is a limit on new accounts where they can only comment once every 10 minutes. And when the bot comments and moves to the next comment to reply to it gets this error:
raise APIException(*errors[0])
praw.exceptions.APIException: RATELIMIT: 'you are doing that too much.
try again in 2 minutes.' on field 'ratelimit'
How can I detect this type of error so the code knows what to do, at the moment the whole script that stops and I have to run it again after 10 minutes.
Had a read of https://praw.readthedocs.io/en/latest/code_overview/exceptions.html but still not getting it
An Exception is raised here, which you can handle using a try..except
try:
the_api_call()
except APIException as e:
print "Handling exception like a baus"
P.S. you would need to import APIException as it's not a in-built exception.
As Samaksh Jain said,
used try..catch
imported APIexception using the following
import django
from rest_framework.exceptions import APIException
The aim
To send custom text messages based on data read in from a csv file. Text messages should only be sent if the recipient is new or if previous messages to the recipient successfully delivered. If the phone number from the csv file is invalid for any reason, the program should just skip to the next number.
The problem
When deployed to Heroku, only the first exception is correctly handled. No messages are sent after the second invalid phone number is processed. However, it appears to work correctly if I run the program locally from the terminal.
The code
def send_sms(num, msg):
# sends message using Twilio's REST API
message = client.messages.create(
to=num,
from_=number,
body=msg,
status_callback=url)
def prep_msg(file):
# iterate through csv file containing phone numbers
for row in file:
msg = 'test message'
num = row[7]
# look for recipient in database of previously sent messages
record = Status.query.filter_by(to=num).first()
if record == None or record.status == 'delivered':
try:
send_sms(num, msg)
except Exception:
continue
return render_template('success.html')
The answer to this was to send the messages asynchronously as a background task using one of Heroku's worker dynos.
I used the following resources to research this:
https://devcenter.heroku.com/articles/python-rq
http://python-rq.org/docs/
I have a two part python standalone application: a publisher and a subscriber.
The publisher generates fake JSON devices objects and published them on a channel called "devices." And as you would guess, the subscriber subscribes to the channel "devices."
(Additionally, given optional command line arguments, the publisher or subscriber can write JSON objects to a socket or a local directory where an Apache Spark Streaming context pickups the JSON objects and processes it. For now, this is not in the picture, as it's optional.)
However, my problem is when my subscriber runs, after the publisher has finished, I get "ERROR: Forbidden".
Here are the respective python code snippets for the publisher:
pubnub = Pubnub(publish_key="my_key", subscribe_key="my_key")
....
pubnub.publish(ch, device_msg)
In the subscriber python file I have the following init code:
def receive(message, channel):
json.dumps(message)
def on_error(message):
print ("ERROR: " + str(message))
....
pubnub = Pubnub(publish_key="my_keys", subscribe_key="my_keys")
# subscribe to a channel and invoke the appropriate callback when a message arrives on that
# channel
#
pubnub.subscribe(channels=ch, callback=receive, error=on_error)
pubnub.start()
While the publisher, when run, seems to publish the JSON messages, all 120 in a loop, whereas the subscriber, when run, seems to fail with the following error message:
ERROR: Forbidden
My attempts to use "demo" keys have made no difference. Note that I'm using a trial account for PubNub.
Since this is one of my first app using its API, has anyone seen this problem before. Surely, something very obvious or trivial is amiss here.
Answer was that there was a copy/paste error with the pub/sub keys.