Related
Problem-
I am using a simple pytesseract + opencv implementation in my discord bot but tesseract is only working when i host it locally. On hosting the file on a remote server (In my case contabo). It shows the following error.
Error-
Extension 'cogs.Wlping' raised an error: ModuleNotFoundError: no module named 'pytesseract'
Code-
async def on_message(msg):
img = cv.imread("test.png")
result = pytesseract.image_to_string(img, lang='eng', config='--psm 11')
await msg.channel.send(result)
I even added tesseract and pytesseract in the requirements.txt file on server. If there is anything else I should do please guide me through.
I write my first bot on Discord.
I use JDA-3.8.1_454-withDependencies.jar
and I try to run the sample from here:
It's a copy/paste and I add my token to the code.
Login is successfull but I got this error:
[main] INFO JDA - Login Successful!
[JDA MainWS-WriteThread] INFO WebSocketClient - Connected to WebSocket
[JDA MainWS-ReadThread] ERROR WebSocketClient - Got an unexpected error. Please redirect following message to the devs:
GUILD_CREATE -> {"default_message_notifications":0,"unavailable":false,"owner_id":"427213800953872415","lazy":true,"roles":[{"color":0,"permissions":104324161,"managed":false,"name":"#everyone","mentionable":false,"position":0,"id":"535169332288946186","hoist":false},{"color":0,"permissions":8,"managed":true,"name":"JRoll Bot","mentionable":false,"position":1,"id":"535178195046105099","hoist":false}],"icon":null,"system_channel_id":"535169332288946188","afk_timeout":300,"features":[],"presences":[{"game":null,"client_status":{"desktop":"idle"},"activities":[],"user":{"id":"427213800953872415"},"status":"idle"},{"game":null,"client_status":{"web":"online"},"activities":[],"user":{"id":"534919677613441045"},"status":"online"}],"afk_channel_id":null,"members":[{"joined_at":"2019-01-16T18:51:51.785000+00:00","roles":[],"deaf":false,"mute":false,"user":{"id":"427213800953872415","avatar":"32d4e5ccb10aad2b4778a9bb71b9f3f5","username":"Hugues","discriminator":"8555"}},{"joined_at":"2019-01-16T18:51:51.785000+00:00","roles":[],"deaf":false,"mute":false,"user":{"id":"427213800953872415","avatar":"32d4e5ccb10aad2b4778a9bb71b9f3f5","username":"Hugues","discriminator":"8555"}},{"nick":null,"joined_at":"2019-01-16T19:27:04.838700+00:00","roles":["535178195046105099"],"deaf":false,"mute":false,"user":{"bot":true,"id":"534919677613441045","avatar":null,"username":"JRoll Bot","discriminator":"3424"}}],"voice_states":[{"self_deaf":false,"user_id":"427213800953872415","deaf":false,"session_id":"8d7b04da746f3cf9281bfeebc418fbf1","mute":false,"suppress":false,"self_video":false,"self_mute":false,"channel_id":"535169332288946190"}],"id":"535169332288946186","member_count":2,"emojis":[],"large":false,"application_id":null,"joined_at":"2019-01-16T19:27:04.838700+00:00","verification_level":0,"explicit_content_filter":0,"channels":[{"permission_overwrites":[],"nsfw":false,"parent_id":null,"name":"Salons textuels","position":0,"id":"535169332288946187","type":4},{"permission_overwrites":[],"last_message_id":"535178254001111040","nsfw":false,"rate_limit_per_user":0,"parent_id":"535169332288946187","name":"général","topic":null,"position":0,"id":"535169332288946188","type":0},{"permission_overwrites":[],"nsfw":false,"parent_id":null,"name":"Salons vocaux","position":0,"id":"535169332288946189","type":4},{"permission_overwrites":[],"nsfw":false,"parent_id":"535169332288946189","name":"Général","bitrate":64000,"position":0,"id":"535169332288946190","user_limit":0,"type":2}],"name":"Test Bot","mfa_level":0,"region":"us-east","splash":null}
java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {OffsetSeconds=0},ISO resolved to 2019-01-16T18:51:51.785 of type java.time.format.Parsed
The bot keeps running but doesnt respond to message in channel.
It's my first bot so it's probably a beginner mistake.
Can someone guide me in the direction to look for ? Thank you.
I'm creating a bot for Discord, and I just wrote this simple code:
import discord
TOKEN = "token"
client = discord.Client()
#client.event
async def on_ready():
print('Bot is ready.')
client.run(TOKEN)
and it produces the following error:
Traceback (most recent call last):
File "/Users/pcaires/Desktop/Programação/Python/Discord Bots/Main.py", line 1, in <module>
import discord
File "/Users/pcaires/Desktop/Programação/Python/Discord Bots/venv/lib/python3.7/site-packages/discord/__init__.py", line 20, in <module>
from .client import Client, AppInfo, ChannelPermissions
File "/Users/pcaires/Desktop/Programação/Python/Discord Bots/venv/lib/python3.7/site-packages/discord/client.py", line 38, in <module>
from .state import ConnectionState
File "/Users/pcaires/Desktop/Programação/Python/Discord Bots/venv/lib/python3.7/site-packages/discord/state.py", line 36, in <module>
from . import utils, compat
File "/Users/pcaires/Desktop/Programação/Python/Discord Bots/venv/lib/python3.7/site-packages/discord/compat.py", line 32
create_task = asyncio.async
^
SyntaxError: invalid syntax
I searched and searched in the internet, and most of the people say to use Python 3.7, and that's what I've been using. Also, I've been using PyCharm as my IDE for Python.
Where does the error come from?
The version of discord.py you are using does not support Python 3.7 (in which async becomes a reserved keyword), as explained in this issue.
This version of discord.py, which is the default branch on the GitHub repo, is sadly the one installed by Pip.
How to fix it
You can either:
downgrade your version of Python to 3.6.
install another version of discord.py, based on the rewrite branch which is under active development, for example with the command : python3 -m pip install --user -U https://github.com/Rapptz/discord.py/archive/rewrite.zip
You can manually edit the file and change that line from create_task = asyncio.async to create_task = getattr(asyncio, 'async')
See more info here: https://github.com/Rapptz/discord.py/issues/1249
Do NOT add asyncio in your requirements, it's already in Python (since 3.5).
It is only relevant for Python 3.3, which does not include asyncio in its stdlib.
As a quick fix you can change asyncio.async to asyncio.ensure_future in the installed offending module and run it. Obviously the right thing to do is get the module updated, but when that's not possible the above will get it running again.
fix it with
pip install --upgrade aiohttp
pip install --upgrade websockets
Today my oauth token is expired but I am unable to regenerate it.
I have a command line tool to interact with the data store on Google Cloud Platform to carry out some support tasks.
Here are the lines of the code that is responsible for the connection
from google.appengine.ext.remote_api import remote_api_stub
remote_api_stub.ConfigureRemoteApiForOAuth(app_name, '/_ah/remote_api')
It prints out these error messages:
INFO:oauth2client.client:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:oauth2client.client:Failed to retrieve access token: {
"error" : "invalid_grant"
}
INFO:google.appengine.tools.appengine_rpc:Got access token error
Traceback (most recent call last):
File "/usr/local/google_appengine/google/appengine/tools/appengine_rpc_httplib2.py", line 247, in Send
url, method=method, body=payload, headers=headers)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/oauth2client/oauth2client/client.py", line 547, in new_request
self._refresh(request_orig)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/oauth2client/oauth2client/client.py", line 775, in _refresh
self._do_refresh_request(http_request)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/oauth2client/oauth2client/client.py", line 840, in _do_refresh_request
raise AccessTokenRefreshError(error_msg)
AccessTokenRefreshError: invalid_grant
Go to the following link in your browser:
https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.apis+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=None&access_type=offline
Enter verification code:
and it follows by a url which it asks me to open in a browser.
When I copy and paste it in chrome, it is all I get
So I tried to run gcloud auth login again. I granted all the access it requested. It seems to work fine.
But when rerun my command line tool, it give the same error message.
So how can I regenerate this 'verification code'?
This fixed my problem
https://stackoverflow.com/a/40493992/58129
Run
gcloud auth application-default login --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email
Trying to figure out the best way to test PubSub push endpoints locally. We tried with ngrok.io, but you must own the domain in order to whitelist (the tool for doing so is also broken… resulting in an infinite redirect loop). We also tried emulating PubSub locally. I am able to publish and pull, but I cannot get the push subscriptions working. We are using a local Flask webserver like so:
#app.route('/_ah/push-handlers/events', methods=['POST'])
def handle_message():
print request.json
return jsonify({'ok': 1}), 200
The following produces no result:
client = pubsub.Client()
topic = client('events')
topic.create()
subscription = topic.subscription('test_push', push_endpoint='http://localhost:5000/_ah/push-handlers/events')
subscription.create()
topic.publish('{"test": 123}')
It does yell at us when we attempt to create a subscription to an HTTP endpoint (whereas live PubSub will if you do not use HTTPS). Perhaps this is by design? Pull works just fine… Any ideas on how to best develop PubSub push endpoints locally?
Following the latest PubSub library documentation at the time of writing, the following example creates a subscription with a push configuration.
Requirements
I have tested with the following requirements :
Google Cloud SDK 285.0.1 (for PubSub local emulator)
Python 3.8.1
Python packages (requirements.txt) :
flask==1.1.1
google-cloud-pubsub==1.3.1
Run PubSub emulator locally
export PUBSUB_PROJECT_ID=fake-project
gcloud beta emulators pubsub start --project=$PUBSUB_PROJECT_ID
By default, PubSub emulator starts on port 8085.
Project argument can be anything and does not matter.
Flask server
Considering the following server.py :
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/_ah/push-handlers/events', methods=['POST'])
def handle_message():
print(request.json)
return jsonify({'ok': 1}), 200
if __name__ == "__main__":
app.run(port=5000)
Run the server (starts on port 5000) :
python server.py
PubSub example
Considering the following pubsub.py :
import sys
from google.cloud import pubsub_v1
if __name__ == "__main__":
project_id = sys.argv[1]
# 1. create topic (events)
publisher_client = pubsub_v1.PublisherClient()
topic_path = publisher_client.topic_path(project_id, "events")
publisher_client.create_topic(topic_path)
# 2. create subscription (test_push with push_config)
subscriber_client = pubsub_v1.SubscriberClient()
subscription_path = subscriber_client.subscription_path(
project_id, "test_push"
)
subscriber_client.create_subscription(
subscription_path,
topic_path,
push_config={
'push_endpoint': 'http://localhost:5000/_ah/push-handlers/events'
}
)
# 3. publish a test message
publisher_client.publish(
topic_path,
data='{"test": 123}'.encode("utf-8")
)
Finally, run this script :
PUBSUB_EMULATOR_HOST=localhost:8085 \
PUBSUB_PROJECT_ID=fake-project \
python pubsub.py $PUBSUB_PROJECT_ID
Results
Then, you can see the results in Flask server's log :
{'subscription': 'projects/fake-project/subscriptions/test_push', 'message': {'data': 'eyJ0ZXN0IjogMTIzfQ==', 'messageId': '1', 'attributes': {}}}
127.0.0.1 - - [22/Mar/2020 12:11:00] "POST /_ah/push-handlers/events HTTP/1.1" 200 -
Note that you can retrieve the message sent, encoded here in base64 (message.data) :
$ echo "eyJ0ZXN0IjogMTIzfQ==" | base64 -d
{"test": 123}
Of course, you can also do the decoding in Python.
This could be a known bug (fix forthcoming) in the emulator where push endpoints created along with the subscription don't work. The bug only affects the initial push config; modifying the push config for an existing subscription should work. Can you try that?
I failed to get PubSub emulator to work on my local env (fails with various java exceptions). I didn't even get to try various features like push with auth, etc. So I end up using ngrok to expose my local dev server and used the public https URL from ngrok in PubSub subscription.
I had no issue with whitelisting and redirects like described in the Q.
So might be helpful for anyone else.