client.run getting timed out (discord.py) - client

i am using
import discord
client=discord.Client()
#client.event
async def on_ready():
print('WE have logged in')
client.run('my token goes here')
But the problem isnt with the script . Because a few days ago it was working fine and i could easily connect to my bot and do stuff . But today i kicked it out and added it again and from then on it doesnt work .
Heres What i did
-I added Outh2 access from the discord dev portal , by copying an url and going there
- Copied the current token and use it
- Authorize / add it again to my server (i know i shouldnt have done this one )
File "/home/soutrik/.local/lib/python3.8/site-packages/discord/client.py", line 640, in run
return future.result()
File "/home/soutrik/.local/lib/python3.8/site-packages/discord/client.py", line 621, in runner
await self.start(*args, **kwargs)
File "/home/soutrik/.local/lib/python3.8/site-packages/discord/client.py", line 584, in start
await self.login(*args, bot=bot)
File "/home/soutrik/.local/lib/python3.8/site-packages/discord/client.py", line 442, in login
await self.http.static_login(token.strip(), bot=bot)
File "/home/soutrik/.local/lib/python3.8/site-packages/discord/http.py", line 261, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "/home/soutrik/.local/lib/python3.8/site-packages/discord/http.py", line 165, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/home/soutrik/.local/lib/python3.8/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/home/soutrik/.local/lib/python3.8/site-packages/aiohttp/client.py", line 582, in _request
break
File "/home/soutrik/.local/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
the error is inside the client.run statement , when i first started out i also faced this same timout error ,but i dont remember how it got solved.
I changed the name and tried after sometime and it worked , which in this case i did try but it didnt work.
Maybe i a doing something entirely different wrongly .

Well um... You kind of need a prefix. Replace client=discord.Client() with client = commands.Bot(command_prefix=['Prefix goes here'])

Related

How do i create a Ticket command in discord.py?

Hello so i want to make a discord bot that can create tickets but i am not sure on how do it i am using discord.py and i was wondering if anyone can help? i have tried this.
#bot.command()
async def ticket(ctx):
await create_text_channel(name, *, overwrites=None, reason=None, **options)
But it does not do anything and i get this error.
Traceback (most recent call last):
File "C:\Users\Robin\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Robin\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 855, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Robin\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'create_text_channel' is not defined```
There are three mistakes in the code you gave:
create_text_channel() is a discord.Guild class method so it only works with a Guild instance
The name variable isn't defined so you'd have an error.
If you don't need any overwrites or any reason, you don't need to write overwrites=None and reason=None, same goes for *.
In the end, your code would look like this:
#bot.command()
async def ticket(ctx):
await ctx.guild.create_text_channel('Channel Name')
I guess you looked at the documentation and copy pasted the method's title, which is unnecessary, you could have looked at the examples given, eg. channel = await guild.create_text_channel('cool-channel')
If you want to create a hidden channel, there's also this example:
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel('secret', overwrites=overwrites)

AWS Lambda EC2-Instances Client Timeout Error

It's very often for me to get error when trying to stop or start ec2-instances through AWS Lambda. Quite strange for me, because sometimes it works (for both start and stop ec2-instances).
The error I get is like below. When I run test on Lambda console, most of the time it successfully executed. But when I run it through AWS Event Rules (CloudWatch), it's very often the function got fail.
This is my code on line 48
[ERROR] ConnectTimeoutError: Connect timeout on endpoint URL: "https://ec2.ap-southeast-2.amazonaws.com/"
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 48, in lambda_handler
if stop_ec2_instances():
File "/var/task/lambda_function.py", line 155, in stop_ec2_instances
ec2_client.stop_instances(InstanceIds=ec2_instances)
File "/var/task/botocore/client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/task/botocore/client.py", line 621, in _make_api_call
http, parsed_response = self._make_request(
File "/var/task/botocore/client.py", line 641, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/var/task/botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/var/task/botocore/endpoint.py", line 136, in _send_request
while self._needs_retry(attempts, operation_model, request_dict,
File "/var/task/botocore/endpoint.py", line 253, in _needs_retry
responses = self._event_emitter.emit(
File "/var/task/botocore/hooks.py", line 356, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "/var/task/botocore/hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "/var/task/botocore/hooks.py", line 211, in _emit
response = handler(**kwargs)
File "/var/task/botocore/retryhandler.py", line 183, in __call__
if self._checker(attempts, response, caught_exception):
File "/var/task/botocore/retryhandler.py", line 250, in __call__
should_retry = self._should_retry(attempt_number, response,
File "/var/task/botocore/retryhandler.py", line 277, in _should_retry
return self._checker(attempt_number, response, caught_exception)
File "/var/task/botocore/retryhandler.py", line 316, in __call__
checker_response = checker(attempt_number, response,
File "/var/task/botocore/retryhandler.py", line 222, in __call__
return self._check_caught_exception(
File "/var/task/botocore/retryhandler.py", line 359, in _check_caught_exception
raise caught_exception
File "/var/task/botocore/endpoint.py", line 200, in _do_get_response
http_response = self._send(request)
File "/var/task/botocore/endpoint.py", line 269, in _send
return self.http_session.send(request)
File "/var/task/botocore/httpsession.py", line 287, in send
raise ConnectTimeoutError(endpoint_url=request.url, error=e)
This is my code for start & stop the instances:
Even, I already move instantiation og ec2_res ec2_client inside the function but it did not help.,
def start_ec2_instances():
try:
ec2_res = boto3.resource('ec2', region_name="ap-southeast-2")
ec2_client = boto3.client('ec2', region_name="ap-southeast-2")
ec2_client.start_instances(InstanceIds=ec2_instances)
for ec2_id in ec2_instances:
instance = ec2_res.Instance(id=ec2_id)
logger.info("Waiting instance " + ec2_id + " to start")
instance.wait_until_running()
return True
except bex.ClientError as err:
logger.error(err.response['Error']['Message'])
return False
def stop_ec2_instances():
try:
ec2_res = boto3.resource('ec2', region_name="ap-southeast-2")
ec2_client = boto3.client('ec2', region_name="ap-southeast-2")
ec2_client.stop_instances(InstanceIds=ec2_instances)
for ec2_id in ec2_instances:
instance = ec2_res.Instance(id=ec2_id)
logger.info("Waiting instance " + ec2_id + " to stop")
instance.wait_until_stopped()
return True
except bex.ClientError as err:
logger.error(err.response['Error']['Message'])
return False
If any one of you ever face the same guys?
Thanks
Edit: I set function timeout to 8 minutes. In normal condition, time required to execute the function is less than 5 minutes.
Additional note:
Sometimes I work using VPN (south-east-2) in which this VPN is in a different region from the region I live. Instances (and another components) also deployed on this region VPN (south-east-2).
Your code to start and stop the instance looks right to me. The timeout is happening because the time taken to perform your operation is not getting completed in the configured timeout for your lambda function.
You can measure what is the time taken for your function by simply subtracting the time between start and stop of the function.
The default timeout is 3 seconds. So you should consider increasing this timeout interval for your lambda function. Say to 5 minutes.
Please note that the maximum value for this timeout is 300 seconds(15 minutes) and you can not configure value higher than this. I am sure the above code would complete within that limit and hence it should not be a problem for you.
How do I increase my timeout interval for my lambda function?
There are multiple ways to do this. By AWS CLI, AWS console, or probably some other way.
In AWS Console you can do like this:
Click on the Save button after doing this change.
Hope this helps.

How do I fix this error with kick command

I wanted to make an kick command but i ran into this error but i couldnt find out how to fix it.
I tried giving permissions to the bot. And giving permissions to me but it all didnt work.
This is my code:
#bot.command(name='kick', aliases=['Kick'])
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member):
await ctx.send('What is the reason?')
msg = await bot.wait_for('message')
reason = msg.content
description = f'''
**Member:** = {member}
**Responsible moderator:** {ctx.author.mention}
**Reason:** {reason}
'''
embed = discord.Embed(title='Kick', description=description)
await ctx.send(content=None, embed=embed)
await member.kick(reason=reason)
This is the error:
Traceback (most recent call last):
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/Guido/Desktop/yeet/overig/coding/discord bots/self coded/oden/code/Oden.py", line 80, in kick
await member.kick(reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 489, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\guild.py", line 1627, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 221, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
It looks like the error is that the bot does not have the permission to kick a user in that server. Make sure that the bot has the Kick Members permission. The bot having permission is the only thing that matters from the API's perspective

why i keep having the same error in that code

i'm following a tutorial course i'm trying to make a web application in python 3.7 that see if there is any bad words in a text file
the text file contains the following text :
-- Houston, we have a problem. (Apollo 13)
-- Mama always said, life is like a box of chocolates. You never know what you are going to get. (Forrest Gump)
-- You cant handle the truth. (A Few Good Men)
-- I believe everything and I believe nothing. (A Shot in the Dark)
import urllib.request
def read_text():
quotes = open (r'C:\Users\M\Desktop\TEMP FILES\movie_quotes.txt')
content_of_file = quotes.read()
print(content_of_file)
quotes.close()
check_profanity(content_of_file)
def check_profanity(text):
connection = urllib.request.urlopen( 'http://www.wdylike.appspot.com/?q='+text)
output = connection.read()
print(output)
connection.close()
read_text()
and i have that error :
Traceback (most recent call last):
File "C:\Users\Mosa Abbas\Desktop\TEMP FILES\ipnd-starter-code-master\ipnd-starter-code-master\stage_3\lesson_3.3_classes\c_profanity_editor\check_profanity.py", line 32, in <module>
read_text()
File "C:\Users\Mosa Abbas\Desktop\TEMP FILES\ipnd-starter-code-master\ipnd-starter-code-master\stage_3\lesson_3.3_classes\c_profanity_editor\check_profanity.py", line 23, in read_text
check_profanity(content_of_file)
File "C:\Users\Mosa Abbas\Desktop\TEMP FILES\ipnd-starter-code-master\ipnd-starter-code-master\stage_3\lesson_3.3_classes\c_profanity_editor\check_profanity.py", line 27, in check_profanity
connection = urllib.request.urlopen( 'http://www.wdylike.appspot.com/?q='+text)
File "C:\Users\Mosa Abbas\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\Mosa Abbas\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 531, in open
response = meth(req, response)
File "C:\Users\Mosa Abbas\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Users\Mosa Abbas\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
File "C:\Users\Mosa Abbas\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Users\Mosa Abbas\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request
what is that error and what i should do to get rid of it
urllib.error.HTTPError: HTTP Error 400: Bad Request
i'v tried to add this line of code :
url = 'http://www.wdylike.appspot.com/?q='+urllib.parse.quote(text, safe = '/')
and then:
connection = urllib.request.urlopen(url)
and i got
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response
i'm a beginner in python and programming web applications so please help :(
When sending a HTTP request through a GET method, it is necessary to escape the GET vars.
So you should probably escape your text before appending it to the URL.
Have a look to question #1695183
i found the solution
I think that happens be because i'm not encoding the string before appending it to the url.
in python3 we should do the following to 'text' before appending it to the url:
text_to_check = urllib.parse.quote_plus(text)
Python2 would be something like this
(urllib was broken into smaller components in python3):
text_to_check = urllib.quote_plus(text_to_check)
This means that, when appending a string with whitespace to the url it will appear as something like "Am+I+cursing%3F" instead of "Am I cursing?".
Full check_profanity() example:
def check_profanity(text_to_check):
text_to_check = urllib.parse.quote_plus(text_to_check)
connection = urlopen(
"http://www.wdylike.appspot.com/?q=" + text_to_check)
output = connection.read()
print(output)
connection.close()

gspread update_cells always return 502 with httpsession error

I am currently trying to overwrite and google spreadsheet with new data using gspread api (version 0.4.1) with sheet.update_cells but it keeps giving me 502 with err msg as follows:
The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds. <ins>That’s all we know.
It seems to be http session problem from the stacktrace:
File "/usr/local/lib/python2.7/dist-packages/gspread/models.py", line 476, in update_cells
self.client.post_cells(self, ElementTree.tostring(feed))
File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 303, in post_cells
r = self.session.post(url, data, headers=headers)
File "/usr/local/lib/python2.7/dist-packages/gspread/httpsession.py", line 81, in post
return self.request('POST', url, data=data, headers=headers)
File "/usr/local/lib/python2.7/dist-packages/gspread/httpsession.py", line 67, in request
response = func(url, data=data, headers=request_headers)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 111, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 475, in request
I did a little bit investigation but it seems that the answer sort of varies, so i think i should better just my version here.
The code snippet is really nothing special like something as follows:
sheet = gspread.authorize(credentials).open_by_key(spreadsheet_key).worksheet(worksheet_title)
if not sheet:
return
if not len(new_rows):
return
sheet.resize(len(new_rows), sheet.col_count)
active_range = 'A1:{0}{1}'.format(last_col, len(new_rows))
cell_list = sheet.range(active_range)
k = 0
for row in new_rows:
for field in row:
cell_list[k].value = field
k+=1
sheet.update_cells(cell_list)
where my new_rows are just the new cell value i want to overwrite the sheet with. I don't think it is an authentication issue, as the same code snippet used to work but somehow at some point it keeps giving the 502.

Resources