Python discord-bot - python-3.9

#-----Import Libraries-----#
import discord
import random
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
client= commands.Bot(command_prefix='#', intents=intents)
#Tictactoe
player1=""
player2=""
turn=""
gameover =True
board=[]
winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
#client.event
async def on_ready():
guild_count = 0
for guild in client.guilds:
print(f' - id: {guild.id} name: {guild.name}')
guild_count+=1
print('Test run is in ' + str(guild_count) + ' servers.')
client.event
async def on_message(message):
if '#tictactoe' in message.content:
global player1
global player2
global turn
global gameover
global count
global board
await message.channel.send('Who do you want to play against?')
try:
message=await client.wait_for('message', check=lambda m: m.author==message.author and m.channel==message.channel, timeout=15)
except asyncio.TimeoutError:
message.channel.send('you ran out of time')
else:
if gameover:
global board
board=[":white_large_square:",":white_large_square:",":white_large_square:",
":white_large_square:",":white_large_square:",":white_large_square:",
":white_large_square:",":white_large_square:",":white_large_square:"]
turn=""
gameover=False
count=0
player1=message.author
player2=message.mentions[0]
#print board
line=""
for x in range(len(board)):
if x==2 or x==5 or x==8:
line+=""+board[x]
await message.channel.send(line)
line=""
else:
line+=""+board[x]
#who goes first
num=random.randint(1,2)
if num==1:
turn=player1
message.channel.send("it is <#"+str(player1.id)+">'s turn")
else:
turn=player2
await message.channel.send("it is <#"+str(player2.id)+">'s turn")
else:
await message.channel.send("A game is already in progress")
#-----Execute bot-----#
client.run('OTMwMDYzMzMzOTY3NjgzNjM0.Ydwa-g.ds5OBaMSOEAUL72AYkSURgrdl54')
And this is the error I keep getting. When i tried the same code in another laptop it worked although i have the same libraries.
Traceback (most recent call last):
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\FIDYAN\python\projecttk.py", line 96, in <module>
client.run('OTMwMDYzMzMzOTY3NjgzNjM0.Ydwa-g.ds5OBaMSOEAUL72AYkSURgrdl54')
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 304, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000024447E19670>
Traceback (most recent call last):
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Nagariamf\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Related

Odoo 12 AttributeError: 'bool' object has no attribute 'ids'

I am trying to get mail when a new record is created and modified for a field in CRM Module so I have defined these functions
in py:
#api.multi
def write (self, vals):
if 'lead_status' in vals and self.ids:
for rec in self:
template = self.env.ref ('crm_extended.crm_lead_mail_template')
template.send_mail (rec.id, force_send = True)
return super (crm_extended, self) .write (vals)
#api.multi
def create (self, vals):
if 'lead_status' in vals and self.ids:
for rec in self:
template = self.env.ref ('crm_extended.create_crm_lead_mail_template')
template.send_mail (rec.id, force_send = True)
return super (crm_extended, self) .write (vals)
when the change the state or give save, odoo popping me an error as below
Error:
Odoo Server Error
Traceback (most recent call last):
File "/opt/odoo/odoo-12.0/odoo/http.py", line 656, in _handle_exception
return super (JsonRequest, self) ._ handle_exception (exception)
File "/opt/odoo/odoo-12.0/odoo/http.py", line 314, in _handle_exception
raise pycompat.reraise (type (exception), exception, sys.exc_info () [2])
File "/opt/odoo/odoo-12.0/odoo/tools/pycompat.py", line 87, in reraise
raise value
File "/opt/odoo/odoo-12.0/odoo/http.py", line 698, in dispatch
result = self._call_function (** self.params)
File "/opt/odoo/odoo-12.0/odoo/http.py", line 346, in _call_function
return checked_call (self.db, * args, ** kwargs)
File "/opt/odoo/odoo-12.0/odoo/service/model.py", line 98, in wrapper
return f (dbname, * args, ** kwargs)
File "/opt/odoo/odoo-12.0/odoo/http.py", line 339, in checked_call
result = self.endpoint (* a, ** kw)
File "/opt/odoo/odoo-12.0/odoo/http.py", line 941, in __call__
return self.method (* args, ** kw)
File "/opt/odoo/odoo-12.0/odoo/http.py", line 519, in response_wrap
response = f (* args, ** kw)
File "/opt/odoo/odoo-12.0/addons/web/controllers/main.py", line 962, in call_kw
return self._call_kw (model, method, args, kwargs)
File "/opt/odoo/odoo-12.0/addons/web/controllers/main.py", line 954, in _call_kw
return call_kw (request.env [model], method, args, kwargs)
File "/opt/odoo/odoo-12.0/odoo/api.py", line 757, in call_kw
return _call_kw_model_create (method, model, args, kwargs)
File "/opt/odoo/odoo-12.0/odoo/api.py", line 737, in _call_kw_model_create
result = method (recs, * args, ** kwargs)
File "<decorator-gen-260>", line 2, in create
File "/opt/odoo/odoo-12.0/odoo/api.py", line 461, in _model_create_multi
return create (self, [arg])
File "/opt/odoo/odoo-12.0/addons/base_automation/models/base_automation.py", line 231, in create
action._process (action._filter_post (records))
File "/opt/odoo/odoo-12.0/addons/base_automation/models/base_automation.py", line 164, in _filter_post
return self._filter_post_export_domain (records) [0]
File "/opt/odoo/odoo-12.0/addons/base_automation/models/base_automation.py", line 169, in _filter_post_export_domain
domain = [('id', 'in', records.ids)] + safe_eval (self.filter_domain, self._get_eval_context ())
AttributeError: 'bool' object has no attribute 'ids'
function:
#api.multi
def create (self, vals):
if 'lead_status' in vals and self.ids:
for rec in self:
template = self.env.ref ('crm_extended.create_crm_lead_mail_template')
template.send_mail (rec.id, force_send = True)
return super (crm_extended, self) .write (vals)
you can not write #api.multi above the create method.
you have to use #api.model.
You tried to use self before calling super and you called the super write method instead of the create method.
Try to correct the create method inheritance:
#api.model
def create(self, vals):
res = super(crm_extended, self).create(vals)
if 'lead_status' in vals:
template = self.env.ref('crm_extended.create_crm_lead_mail_template')
for record in res:
template.send_mail (record.id, force_send=True)
return res

Number Guessing Game with discord.py rewrite

I tried this code, bot says guess but doesn't respond to my guess.
#commands.command()
async def game(self, ctx):
number = random.randint(0, 100)
for guess in range(0, 5):
await ctx.send('guess')
Message = await bot.wait_for('message')
Message = int(Message)
if Message.cleant_content > number:
await ctx.send('bigger')
elif Message.cleant_content < number:
await ctx.send('smaller')
else:
await ctx.send('true')
Because you're using cogs, I'd imagine you've got your bot initialised as self.bot instead of just bot.
Also, you're converting a message object to an integer, and trying to access an attribute of an integer named cleant_content.
This is how your code should look:
#commands.command()
async def game(self, ctx):
number = random.randint(0, 100)
for i in range(0, 5):
await ctx.send('guess')
response = await self.bot.wait_for('message')
guess = int(response.content)
if guess > number:
await ctx.send('bigger')
elif guess < number:
await ctx.send('smaller')
else:
await ctx.send('true')
I also changed up a few of the variable names for readability purposes. If you want to, you can add some checks for whether their guess was actually a number or not.
Additionally, I changed what was meant to be clean_content to content instead, as clean_content is completely void of its purpose because you can't convert <, #, #, !, > and such to an integer, meaning it would error either way. I'm hoping that made some sense.
References:
Client.wait_for()
Message.content
Message.clean_content - Read the difference between content and clean_content to better understand what I was getting at
This Is Another Way:
#bot.command()
async def game(ctx, *, number=0):
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
correct_number = random.choice(number_list)
if number == correct_number:
embedVar = discord.Embed(title=f'Your Number Is {number}', color=0xFF0000)
embedVar.add_field(name='You Picked The Correct Number! You Won', value="Thanks For Playing!")
await ctx.send(embed=embedVar)
else:
embedVar = discord.Embed(title=f'Your Number Is {number}', color=0xFF0000)
embedVar.add_field(name="Sorry, You Picked The Wrong Number", value="Thanks For Playing")
await ctx.send(embed=embedVar)
I did my guess command like this:
#bot.command()
async def guess(ctx):
await ctx.send("Guess the number from 1 to 10!")
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
choice = random.choice(numbers)
answer = await bot.wait_for("message")
if answer.content == choice:
await ctx.send("You guessed the correct number!")
else:
await ctx.send(f"You lost! The number was {choice}")
You need to install random:
#bot.command()
async def guess(ctx, msg : int = None):
num_list = [1,2,3,4,5,6,7,8,9,10]
number = (num_list[randint(0, num_list.__len__()-1)])
print(number)
if msg > number:
await ctx.send("Try again you were to high")
if msg < number:
await ctx.send("Try again you were to low")
if msg == number:
await ctx.send("You were right")
await ctx.send(f'The Number is {number}')

Getting Uninitialized Constant Error in Ruby Program - why can't I format a number?

This field
def format_to_two_dec(stringfield)
"%.2f" % stringfield # -> CRASHES
stringfield #--> OKAY - returns a string such as 900
end
This code calls a record with a field called total in it.
return_method =
proc do |the_self_ref|
the_record = the_self_ref.peek_next_db_record.select do |an_elem|
an_elem[:crectype] == '0004'
end
the_self_ref.format_to_two_dec(the_record[0][:total])
end
What I'm trying to do is to format the number to have two decimals and ALWAYS two decimals (so 900.00).
The error I get is:
//Scripts/create_835_record.rb:168:in `block (2 levels) in eval_x12_commands': uninitialized constant Create835Records::C (NameError)
The format of the record is:
record0004_format =
{
ctotal_charge: 15,
cdiscount: 15,
cineligible: 15,
cpended: 15,
callowed: 15,
cdeductible: 15,
ccopay: 15,
ccoinsurance: 15,
cbalance: 15,
cother_carrier: 15,
cpayment: 15,
cpatient_responsibility: 15,
primarypayment: 15,
excess: 15,
noncovered: 15
}
def eval_x12_commands
#list_of_segments_in_file.each do |a_cmd|
array_to_eval = a_cmd.split('|')
list_of_evaled = []
array_to_eval.each do |item|
**list_of_evaled << eval(item, binding)** //this line
end
the_method = #the_builder_for835.method(list_of_evaled[0])
begin
the_method.call(*list_of_evaled[1..-1])
rescue
puts "Eval Exception\n"
end
end
I hope this will be enough - the program is a bit big, but I can post more if I need to.

Collecting keyword arguments in Ruby

Just trying to understand how to collect arguments in Ruby, I came up with the following snippet, that seems to fail to collect keyword arguments in **kargs in some case:
def foo(i, j= 9, *args, k: 11, **kargs)
puts "args: #{args}; kargs: #{kargs}"
end
foo(a: 7, b: 8)
# output: args: []; kargs: {}
foo(9, a: 7, b: 8)
# output: args: []; kargs: {:a=>7, :b=>8}
foo(9, 10, 13, a: 7, b: 8)
# output: args: [13]; kargs: {:a=>7, :b=>8}
I would like to know why it does not collect kargs in the first call to foo, while in the second call it does.
It's because the first parameter i, is a required parameter (no default value), so, the first value passed to the method (in your first example, this is the hash {a: 7, b: 8}) is stored into it.
Then, since everything else is optional, the remaining values (if any, in this example, there are none) are filled in, as applicable. IE, the second parameter will go to j, unless it is a named parameter, then it goes to kargs (or k). The third parameter, and any remaining--up until the first keyword argument, go into args, and then any keyword args go to kargs
def foo(i, j= 9, *args, k: 11, **kargs)
puts "i: #{i}; args: #{args}; kargs: #{kargs}"
end
foo(a: 7, b: 8)
# i: {:a=>7, :b=>8}; args: []; kargs: {}

How to limit the downloading speed as slow as getting 20 urls per minute for the scrapy?

Here is my scrapy struture,to ommit concret statements,to keep the main structure visible, to save it as test.py.
import scrapy,urllib.request
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 3
AUTOTHROTTLE_MAX_DELAY = 6
CONCURRENT_REQUESTS_PER_IP = 1
CONCURRENT_REQUESTS = 1
CONCURRENT_REQUESTS_PER_SPIDER = 1
CLOSESPIDER_PAGECOUNT = 100000
CLOSESPIDER_TIMEOUT = 36000
DOWNLOAD_DELAY = 3
RETRY_ENABLED = False
COOKIES_ENABLED = False
RETRY_ENABLED = True
RETRY_TIMES = 1
COOKIES_ENABLED = False
class TestSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["some web"]
def __init__(self, *args, **kw):
self.timeout = 10
def start_requests(self):
yield scrapy.Request(url,callback=self.parse)
def parse(self, response):
do something
The info abstract on my console when running it with command scrapy runspider test.py.
'downloader/request_count': 3391,
'finish_time': datetime.datetime(2017, 10, 25, 12, 29, 43, 101017),
'start_time': datetime.datetime(2017, 10, 25, 12, 24, 10, 63516)}
total time = 29min-24min+(43-10)=5min33second=333 seconds
total request =3391
We draw the conclusion that it can run as quickly as getting 10 urls per second.
Why DOWNLOAD_DELAY = 3,and AUTOTHROTTLE_ENABLED = True,AUTOTHROTTLE_START_DELAY = 3 and AUTOTHROTTLE_MAX_DELAY = 6 can't slow down the speed?
How to limit the downloading speed as slow as getting 20 urls per minute?
Please try removing redundant settings (for example CONCURRENT_REQUESTS_PER_SPIDER is already deprecated) try this spider, it's upper bounded to 20 requests per minute:
import scrapy
from datetime import datetime
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/',
]
custom_settings = {
'CONCURRENT_REQUESTS': 1,
'DOWNLOAD_DELAY': 3,
'AUTOTHROTTLE_ENABLED': False,
'RANDOMIZE_DOWNLOAD_DELAY': False
}
def parse(self, response):
self.logger.debug('%s', datetime.utcnow())
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('span small::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
}
next_page = response.css('li.next a::attr(href)').extract_first()
if next_page is not None:
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

Resources