Discord.py bot is missing permission? - discord.py

I tried to do an autorole system for my discord bot and my code looks like that:
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "#", intents = intents)
#client.event
async def on_member_join(member):
server_name = client.get_guild(802985801100165200)
await member.send(f'Willkommen auf {server_name}!')
print(1)
rolle = discord.utils.get(member.guild.roles, name='Member')
await member.add_roles(rolle)
I get this as an error:
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\wenze\PycharmProjects\discordbotproject\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\wenze\PycharmProjects\discordbotproject\main.py", line 34, in on_member_join
await member.add_roles(rolle)
File "C:\Users\wenze\PycharmProjects\discordbotproject\venv\lib\site-packages\discord\member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\wenze\PycharmProjects\discordbotproject\venv\lib\site-packages\discord\http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

Your issue is either
The bot doesn't have the Manage Roles permissions
To fix this just reinvite your bot with the correct permissions.
The role that the bot is trying to give is above the bot in hierarchy.
You can handle this error by using a try except block looking like:
try:
Member.add_roles(role)
except discord.Forbidden:
# This will be triggered when the bot has incorrect permissions.

Hei
I have had that issue too with my node.js bot, where I could not give roles to any of my server's members.
I kicked the bot out of the server, I went in this page here and gave my bot all permissions (for simplicity I marked every checkbox). I then copied my bot Client ID and pasted in the required field. I pressed the link at the bottom of the page to call it back into my server. That fixed my issue

Related

AppStudioPlugin.DeveloperPortalAPIFailed after upgrading Teams Toolkit to 4.2.0

After upgrading Teams Toolkit to 4.2.0, while debugging team Application in Visual studio code, it fails with
API call to Developer Portal failed: Error, Request failed with status code 403, API name: create-app, X-Correlation-ID: undefined. This may come from some intermittent service error. Please wait for a few minutes and retry the current step. data: "<%3Fxml version="<REDACTED: user-file-path>" encoding="<REDACTED: user-file-path>"%3F>\nAuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the <REDACTED: user-file-path>:<REDACTED: user-file-path>:2022-12-21T17:17:27.0783537ZAuthentication scheme Bearer is not supported in this version."
stack:
DeveloperPortalAPIFailed: API call to Developer Portal failed: Error, Request failed with status code 403, API name: create-app, X-Correlation-ID: undefined. This may come from some intermittent service error. Please wait for a few minutes and retry the current step. data: "<%3Fxml version="<REDACTED: user-file-path>" encoding="<REDACTED: user-file-path>"%3F>\nAuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the <REDACTED: user-file-path>:<REDACTED: user-file-path>:2022-12-21T17:17:27.0783537ZAuthentication scheme Bearer is not supported in this version."
at AppStudioResultFactory.SystemError (<REDACTED: user-file-path>:2:7338905)
at wrapException (<REDACTED: user-file-path>:2:7304721)
at Object.importApp (<REDACTED: user-file-path>:2:7308431)
at process.processTicksAndRejections (node:<REDACTED: user-file-path>:96:5)
at async Object.createTeamsApp (<REDACTED: user-file-path>:2:7286749)
at async AppManifest.provision (<REDACTED: user-file-path>:2:7258303)
at async AppManifest. (<REDACTED: user-file-path>:2:6625833)
at async TeamsfxCore.provision (<REDACTED: user-file-path>:2:6128194)
at async TeamsfxCore. (<REDACTED: user-file-path>:2:6625833)
at async FxCore.provisionResourcesOld (<REDACTED: user-file-path>:2:7628193)
at async FxCore. (<REDACTED: user-file-path>:2:7772838)
at async exports.ProjectSettingsWriterMW (<REDACTED: user-file-path>:2:7846344)
at async exports.ContextInjectorMW (<REDACTED: user-file-path>:2:7761355)
at async FxCore. (<REDACTED: user-file-path>:2:7768296)
at async exports.VideoFilterAppBlockerMW (<REDACTED: user-file-path>:2:7896895)
at async exports.ProjectSettingsLoaderMW (<REDACTED: user-file-path>:2:7844791)
at async exports.ProjectVersionCheckerMW (<REDACTED: user-file-path>:2:7849870)
at async exports.AadManifestMigrationMW (<REDACTED: user-file-path>:2:7740883)
at async exports.ProjectConsolidateMW (<REDACTED: user-file-path>:2:7761067)
at async exports.ProjectMigratorMW (<REDACTED: user-file-path>:2:7810098)
at async exports.ConcurrentLockerMW (<REDACTED: user-file-path>:2:7743579)
at async exports.ErrorHandlerMW (<REDACTED: user-file-path>:2:7774291)
While debugging teams app in visual studio code, it should load the application in Microsoft Teams. Instead it is failing. This is after upgrading Team Toolkit to v4.2.0

Botframework | Twilio WhatsApp Adapter: how to fix "request doesn't contain a valid Twilio Signature"

I need to use Twilio as a channel for a chatbot (Bot Framework V4 NodeJS and the Twilio WhatsApp Adapter)
Messages send to Twilio via WhatsApp do reach the chatbot as a request. In the chatbot itself the validation of the request keeps failing.
const { TwilioWhatsAppAdapter } = require('#botbuildercommunity/adapter-twilio-whatsapp');
const whatsAppAdapter = new TwilioWhatsAppAdapter({
accountSid: '<Sid from Twilio console >',
authToken: '<>Auth token from Twilio console',
phoneNumber: '<phone number from Whatsapp Sandbox settings in Twilio>',
endpointUrl: 'url from Sandbox setting in Twilio'
});
The adapter is using a Twilio module. Twilio.validateRequest keeps returning false.
const signature = req.headers['x-twilio-signature'] || req.headers['X-Twilio-Signature'];
const authToken = this.settings.authToken;
const requestUrl = this.settings.endpointUrl;
const message = await this.retrieveBody(req);
return Twilio.validateRequest(authToken, signature, requestUrl, message);
I would appreciate some guidance. Otherwise I will need to figure our a way to debug this module
tnx
For the endpointUrl parameter I use is the one from my chatbot: https://mybot.azurewebsites.net/api/whatsapp/messages
for the phoneNumber parameter I tried multiple formats without succes:
whatsapp:+1XXXXXXXXXX
whatsapp:1XXXXXXXXXX
+1XXXXXXXXXX
1XXXXXXXXXX
I checked the source of the adapter and there are two possible causes.
No x-twilio-signature header. I checked the request headers and there seems to be a valid x-twilio-signature header in there.
The result of the twilio.validateRequest returns false. This method is taking authToken, signature, requestUrl and message. I checked them all and they seem fine.

System.Net.Http.HttpRequestException: '404 (Not Found)'

I used this tutorial to create a Google Login for my App with Xamarin:
Authenticate users through Google with Xamarin.Auth
I did it step by step but at the end, After I sign in to my google account I get this error:
System.Net.Http.HttpRequestException: '404 (Not Found)'
This part of code returns the error... When it tries to get the Email from API:
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
var json = await httpClient.GetStringAsync("https://www.googleapis.com/userinfo/email?alt=json");
var email = JsonConvert.DeserializeObject<Email>(json);
return email.Data.Email;
My config parameters:
Google Client Id is correct => 437067938756-....apps.googleusercontent.com
Google Scope is "email"
GoogleRedirectUrl is blahbal:/oauth2redirect => blahblah is myAndroidManifest
GoogleAuthorizeUrl is"https://accounts.google.com/o/oauth2/v2/auth";
GoogleAccessTokenUrl is "https://www.googleapis.com/oauth2/v4/token";
GoogleIsUsingNativeUI is true
I was having the same error at some point.
The issue was in incorrect certificate.
Check if you are signing your app with Dev or Prod certificate.
Or you've updated/reinstalled xamarin and your dev cert has changed.

Django token authorization - customizing obtain_jwt_token by overriding ObtainAuthToken class

My goal is to override obtain_jwt_token in order to get more control over the return value of the procedure, and in the doc I found only a bizarre and sketchy info on how to do this:
Note that the default obtain_auth_token view explicitly uses JSON
requests and responses, rather than using default renderer and parser
classes in your settings. If you need a customized version of the
obtain_auth_token view, you can do so by overriding the
ObtainAuthToken view class, and using that in your url conf instead
As for now, my attempt looks like this:
urlpatterns = [
url(r'^api-token-auth/', my_customized_view),
]
class Foo(ObtainAuthToken):
def post(self):
# here goes my customized code
my_customized_view = Foo.as_view()
The odds are that my code looks quite silly, and I am just lost trying to google it. I have little experience in Djagno, so please help me with this !
I have just been going through the same journey for comprehension as I wished to return the user and also allow email or username login. The documentation is not entirely clear, but as described for auth token, you can do the same for JWT.
obtain_auth_token is to ObtainAuthToken, as obtain_jwt_token is to ObtainJSONWebToken.
This is my overwritten login method:
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
class LoginView(ObtainJSONWebToken):
def post(self, request, *args, **kwargs):
# by default attempts username / passsword combination
response = super(LoginView, self).post(request, *args, **kwargs)
# token = response.data['token'] # don't use this to prevent errors
# below will return null, but not an error, if not found :)
res = response.data
token = res.get('token')
# token ok, get user
if token:
user = jwt_decode_handler(token) # aleady json - don't serialize
else: # if none, try auth by email
req = request.data # try and find email in request
email = req.get('email')
password = req.get('password')
username = req.get('username')
if email is None or password is None:
return Response({'success': False,
'message': 'Missing or incorrect credentials',
'data': req},
status=status.HTTP_400_BAD_REQUEST)
# email exists in request, try to find user
try:
user = User.objects.get(email=email)
except:
return Response({'success': False,
'message': 'User not found',
'data': req},
status=status.HTTP_404_NOT_FOUND)
if not user.check_password(password):
return Response({'success': False,
'message': 'Incorrect password',
'data': req},
status=status.HTTP_403_FORBIDDEN)
# make token from user found by email
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
user = UserSerializer(user).data
return Response({'success': True,
'message': 'Successfully logged in',
'token': token,
'user': user},
status=status.HTTP_200_OK)
You can change the default to check by email only if you please by customising Django's auth model, but I was happy to have both options.
I started creating an api boilerplate. There is a requirements.txt file and a config.example.py file for anyone who wants to pull it down to view the rest.
https://github.com/garyburgmann/django-api-boilerplate
In views.py, file add the following code and customize as you want.
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserSerializer(user, context={'request': request}).data
}
Default is {'token': token}
Also In your settings.py file add
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER':
'api.user.views.jwt_response_payload_handler',
}
( 'api.user.views.jwt_response_payload_handler',
) is the path to your custom jwt_response_payload_handler
For more help, you can view here

WireCloud and Horizon behind HTTPS proxy

We have a proxy running that serves HTTPS pages to the internet. Therefore it redirects requests into our DMZ where the pages are served as HTTP pages.
We got WireCloud set up to run at a subdomain: wirecloud.example.com. Horizon runs at horizon.example.com.
In Horizon the Callback URL is set to: http://wirecloud.example.com/complete/fiware/ and in the settings.py of Wirecloud the FIWARE_IDM_SERVER = 'http://horizon.example.com' is set.
Now, when wirecloud.example.com/login gets called, it is redirected to https by our proxy and then redirected to horizon by wireclound what then gets redirected by our proxy to https://horizon.example.com/oauth2/authorize/?state=STATE_KEY&redirect_uri=http://wirecloud.example.com/complete/fiware/&response_type=code&client_id=CLIENT_ID. If the user is not logged in and now does so the redirect_uri gets transformed to this: http%253A%252F%252Fwirecloud.example.com%252Fcomplete%252Ffiware%252F what leads to this error: {"state": "STATE_KEY", "error": "invalid_redirect_uri"} (HTTP 400). If the user is already logged in and tries to authorize the app (WireCloud) a 405 error gets thrown:
Environment:
Request Method: GET
Request URL: http://wirecloud.example.com/complete/fiware/?state=STATE_KEY&code=CODE
Django Version: 1.9.6
Python Version: 2.7.9
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'wirecloud.commons',
'compressor',
'wirecloud.catalogue',
'wirecloud.platform',
'wirecloud.oauth2provider',
'wirecloud.fiware',
'social.apps.django_app.default')
Installed Middleware:
('wirecloud.commons.middleware.URLMiddleware',)
Traceback:
File "/opt/wc/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/opt/wc/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/apps/django_app/utils.py" in wrapper
51. return func(request, backend, *args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/apps/django_app/views.py" in complete
28. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/actions.py" in do_complete
43. user = backend.complete(user=user, *args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/backends/base.py" in complete
41. return self.auth_complete(*args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/utils.py" in wrapper
229. return func(*args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/backends/oauth.py" in auth_complete
383. method=self.ACCESS_TOKEN_METHOD
File "/opt/wc/venv/lib/python2.7/site-packages/social/backends/oauth.py" in request_access_token
361. return self.get_json(*args, **kwargs)
File "/opt/wc/venv/lib/python2.7/site-packages/social/backends/base.py" in get_json
229. return self.request(url, *args, **kwargs).json()
File "/opt/wc/venv/lib/python2.7/site-packages/social/backends/base.py" in request
225. response.raise_for_status()
File "/opt/wc/venv/lib/python2.7/site-packages/requests/models.py" in raise_for_status
844. raise HTTPError(http_error_msg, response=self)
Exception Type: HTTPError at /complete/fiware/
Exception Value: 405 Client Error: METHOD NOT ALLOWED for url: https://horizon.example.com/oauth2/token
So how do we need to configure WireCloud and/or Horizon and/or our proxy to get this to work?
Edit your settings.py file and add the following lines for forcing WireCloud to use https for the internal urls:
FORCE_PROTO = 'https'
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True
This should make WireCloud to use https://wirecloud.example.com/complete/fiware/ as the redirect_uri. See the FORCE_PROTO for more details.
Regarding, this exception:
Exception Type: HTTPError at /complete/fiware/
Exception Value: 405 Client Error: METHOD NOT ALLOWED for url: https://horizon.example.com/oauth2/token
I need more info for being 100% sure, but seems a problem regarding network visibility. I think that the WireCloud machine is requesting the https://horizon.example.com/oauth2/token URL, but this request is not passing through your proxy/frontend server. You can confirm this case, if you have a valid token, by executing the following line from the WireCloud machine and from an external machine:
curl -v https://horizon.example.com/oauth2/token?access_token=*****

Resources