I am trying to deploy this Telegram bot* on Heroku: https://github.com/radinshayanfar/TGCopyBot. The bot first needs to sign in to my account, which requires a login code that's sent to my devices on which I'm already logged in. When running the bot locally from a terminal, it requests input from the user, Enter code:, upon which I enter the login code in the terminal and press Enter, and the bot proceeds to do its work. But after deploying the bot on Heroku and running the dyno, it fails and this shows in the logs:
2021-06-26T12:55:33.312544+00:00 app[worker.1]: Enter code:Traceback (most recent call last):
2021-06-26T12:55:33.312546+00:00 app[worker.1]: File "/app/app/main.py", line 77, in <module>
2021-06-26T12:55:33.312729+00:00 app[worker.1]: tg.login()
2021-06-26T12:55:33.312730+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/telegram/client.py", line 493, in login
2021-06-26T12:55:33.312946+00:00 app[worker.1]: result = actions[authorization_state]()
2021-06-26T12:55:33.312948+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/telegram/client.py", line 585, in _send_telegram_code
2021-06-26T12:55:33.313163+00:00 app[worker.1]: code = input('Enter code:')
2021-06-26T12:55:33.313168+00:00 app[worker.1]: EOFError: EOF when reading a line
2021-06-26T12:55:33.373308+00:00 heroku[worker.1]: Process exited with status 1
2021-06-26T12:55:33.427790+00:00 heroku[worker.1]: State changed from up to crashed
It may then automatically start the bot again, and proceed to crash and output the same errors as above. What's the problem here, and how can it be fixed?
If the issue is its request for the login code, then I do receive the login code on my other devices, but how do I give the login code to the bot? More generally, how do you repsond to a request for user input from any bot deployed on Heroku?
*not really a Telegram bot made with #BotFather; it just uses the Telegram API development tools
On your local environment, the built-in input works fine because you have access to the Terminal and can provide the input.
On Heroku there is no such an option so the command returns the EOFError exception because the function hits the end-of-file condition (EOF) without reading anything.
A possible solution might be to request the user to enter the login code via the Telegram Bot, for example as first step after the user starts chatting.
It seems the issue is with the request for user input, and that there is no direct way for the user to input anything on Heroku as they would on a terminal. The code can be modified to accept what would be inputted as an environment variable in this case, by using e.g. a session string: https://docs.pyrogram.org/topics/storage-engines#session-strings, https://docs.telethon.dev/en/latest/concepts/sessions.html#string-sessions
Related
I'm trying to authenticate to SharePoint Online. Using sharepy v 2.0, pyCharm community edition, and python 3.9.
When I run:
'sharepy.connect('siteurl')'
From within PyCharm, Sharepy will freeze after I input my username in the run dialog box.
If I add the 'username' parameter and run it. Nothing happens. I'm never prompted for a password
If I use the console and enter in sharepy.connect('siteurl') then username and password (same goes for passing those parameters) I will get an error:
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 75, in _get_token
token = root.find('.//wsse:BinarySecurityToken', ns).text
AttributeError: 'NoneType' object has no attribute 'text'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\session.py", line 15, in connect
return SharePointSession(site, auth=autoauth)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\session.py", line 61, in __init__
self.auth.login(self.site)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 27, in login
self._get_token()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 77, in _get_token
raise errors.AuthError('Token request failed. Invalid server response')
sharepy.errors.AuthError: Token request failed. Invalid server response
It should be noted I'm getting O365 from godaddy and the login page is federated? I think is the correct term.
According to the new release of Sharepy, this shouldn't matter.
Has anyone else had this freezing problem happen for them?
How would I authenticate with sharepoint using sharepy given my current situation?
The source of this problem ended up being GoDaddy. As we were federated using GoDaddy as the O365 provider. There was no way to authenticate correctly using sharepy.
The ultimate solution was to defederate away from GoDaddy (pretty easy to do thanks to this guy: Defederation Guide)
The reason we were unable to authenticate was because our provider redirects the login to their own login site. And unfortunately the sharepy builtin method of "auth" wouldn't work with GoDaddy.
I tested this theory before migrating away from GoDaddy. By using a fresh tenant. I also found that when you enable MFA the password/username method of authentication doesn't work.
NOTE: When new tenants are created they utilize a blanket security protocol which forces MFA. Even though MFA is shown as disabled in the Azure AD > Users section. To turn this off you must disable "Security Defaults": portal.azure.com > Azure Active Directory > Properties > "Manage security defaults" (at the bottom of the screen, its a small hyperlink).
A note on MFA and authentication with sharepy. There are methods to leave MFA enabled which work with other sharepoint/python things. I haven't tested them using sharepy yet, but will be turning on MFA and using one of the following methods:
App Password
Sharepoint API client secret
Azure App Registration (Azure App Reg)
I am making a simple slack bot using github action:
But every time I tried to post a message to my channel, the error ocurrs
Traceback (most recent call last):
File "4_distributed_mlblogbot_to_py_update.py", line 130, in <module>
text = "{0} \n*{1}* \n<{2}|{3}> :bell:".format(today, bible1, 'https://sum.su.or.kr:8888/bible/today' , script) )
File "/opt/hostedtoolcache/Python/3.6.12/x64/lib/python3.6/site-packages/slacker/__init__.py", line 515, in post_message
'mrkdwn': mrkdwn,
File "/opt/hostedtoolcache/Python/3.6.12/x64/lib/python3.6/site-packages/slacker/__init__.py", line 126, in post
api, **kwargs
File "/opt/hostedtoolcache/Python/3.6.12/x64/lib/python3.6/site-packages/slacker/__init__.py", line 102, in _request
raise Error(response.error)
slacker.Error: account_inactive
So everytime I try, I reinstall the app and invite my bot to mychannel
But It doesn't work
Meanwhile, In my personal python env(ex, colab) there are no errors.
Should I give up the token based BOT and get the webhook based bot?
Thank you
Every time I get a new auth(ex webhooks, tokens) and I run the github action, Always failed about the auth.
The hint was my "blabla.py" and the failed alarm email
I mistakenly expose my auth(IT SHOULD BE A SECRET) and Github and slack automatically drop my auth for security issue.
So after I used secret function in Github action, It works
I'm using the following Python code from Slack's "Migrating to 2.x" github docs
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
client = SlackClient(slack_token)
def say_hello(data):
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
client.api_call('chat.postMessage',
channel=channel_id,
text="Hi <#{}>!".format(user),
thread_ts=thread_ts
)
if client.rtm_connect():
while client.server.connected is True:
for data in client.rtm_read():
if "type" in data and data["type"] == "message":
say_hello(data)
else:
print "Connection Failed"
For the SLACK_API_TOKEN, I am using the Bot User OAuth Access Token for my app, found here:
The error I am getting is the following:
Failed RTM connect
Traceback (most recent call last):
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/server.py", line 168, in rtm_connect
raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed
Why am I getting this error?!?!?!
Other context:
I am on a Mac, unlike others who have had issues online using Windows
machines.
I am running the code locally, in a virtual env, via
python script.py in my terminal.
I last successfully ran this in December, and have seen that Slack dropped support for the RTM API (?) Dec 31st 2019?
The app has been reinstalled to my workspace, and the keys did not change.
I think it may be something I need to configure/change/set/refresh on the api.slack.com/apps side, since it broke without any code changes occurring.
Why am I focusing on debugging the example for 1.x? My code was previously working using rtm_connect / 1.x using the same commands as the example code, and without any code changes it has stopped working. My code and the example code yield the same errors, so I'm using the sample code to make debugging easier. I'd like to fix this before starting the process of migrating to 2.x, so I can start with working code before embarking on a long series of changes that can introduce their own errors.
I do not think this issue is related to the Bot User OAuth Access Token, in my view you are using the right one (xoxb-). However, this issue might be related to the Slack App. Note that RTM isn't supported for the new Slack App granular scopes (see python client issue #584 and node client issue #921). If you want to use RTM, you should create rather a classic slack app with the OAuth Scope bot.
I not sure if this is the reason, but I ran into the same issues before.
The answer I found on the Slack Github is that new xoxob-* doesn't support RTM.
Please reference this web:
- https://github.com/slackapi/python-slackclient/issues/326.
So I use my OAuth Access Token instead of Bot User OAuth Access Token.
I'm using boto3 to create an IAM user, wait until the IAM user is created, then update the login profile of that user. My python code to create the user works fine, and the user is created successfully. IAM is eventually consistent, so I know that I need to wait for the user to be created before I can do anything else with it, and I am using a waiter for that purpose. But when I try to update the login profile, it errors out saying that the user doesn't exist yet.
So basically the waiter isn't waiting like it should.
Anyone know what I'm doing wrong here?
import boto3
password = 'not_the_real_password'
client = boto3.client('iam')
# Create the user
response = client.create_user(
UserName='someuser'
)
# Creating the user works fine. But IAM is eventually consistent, so we have
# to wait for the user to be created before we can do anything with it.
waiter = client.get_waiter('user_exists')
waiter.wait(UserName='someuser')
# If the waiter worked correctly, then it should have waited for the user
# to be created before updating the login profile.
response = client.update_login_profile(
UserName='someuser',
Password=password,
PasswordResetRequired=True
)
Expected result: the waiter should wait long enough that the IAM user exists, and then updating the login profile would work as expected.
Actual result:
Traceback (most recent call last):
File "add_user.py", line 20, in <module>
PasswordResetRequired=True
File "/home/myuser/.local/lib/python3.6/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/home/myuser/.local/lib/python3.6/site-packages/botocore/client.py", line 661, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.NoSuchEntityException: An error occurred (NoSuchEntity) when calling the UpdateLoginProfile operation: Login Profile for User someuser cannot be found.
The error says:
Login Profile for User someuser cannot be found.
The Login Profile is separate to the User. It needs to be specifically created.
Change update_login_profile() into create_login_profile().
I'm trying to make a simple program to post something to my wall on Fcebook in Python. I tried using this example from pythonforfacebook:
import facebook
oauth_access_token = "****"
graph = facebook.GraphAPI(oauth_access_token)
me = "****"
profile = graph.get_object(me)
graph.put_object(me, "feed", message="I am writing on my wall!")
I tried going to the developer center and making an App. For "Select how your app integrates with Facebook",I chose "Website with Facebook Login" (I don't actually have a website, I just have a program that should post to my facebook wall, but this is the closest option that matches what I want to do...).
However, when I run this, it says:
$ python a.py
Traceback (most recent call last):
File "a.py", line 7, in <module>
graph.put_object(me, "feed", message="I am writing on my wall!")
File "/usr/lib64/python2.7/site-packages/facebook.py", line 140, in put_object
post_args=data)
File "/usr/lib64/python2.7/site-packages/facebook.py", line 298, in request
raise GraphAPIError(response)
facebook.GraphAPIError: (#200) The user hasn't authorized the application to perform this action
How can I log in as the user and authorize my App? Am I even taking the right approach? I don't actually have a website, I just have a program, for the website field I literally entered "http://google.com" and it worked.
I made it work by getting a new token with permissions to post on my wall (specifically, the "publish_actions" permission). I did this by using the Graph API Explorer, selecting my application in the dropdown menu, pressing "Get Access Token" and checking "publish_actions". The only problem is the token expires after an hour.
You must authorize the user for publish_action/publish_stream permission to post on your wall.
If your only task is to post on the wall/ get the basic info; you can use the APP Access Token instead of user access token for performing the action once you've authorized the app. To get the App Access Token, you can uuse-
GET /oauth/access_token?
client_id={app-id}
&client_secret={app-secret}
&grant_type=client_credentials
Or, directly from here. But do not hard code it in your app (for security reasons)
Or, if you want to perform other actions too on the user's behalf you can extend the user token to 2 months validity. Read here for more details
For those of who stumble upon this post after April 24th, Facebook has stopped support for such API calls.
As of April 24,2018, the publish_actions permission has been removed. Please see the Breaking Changes Changelog for more details. To provide a way for your app users to share content to Facebook, we encourage you to use our Sharing products instead.