How to send a discord.js random embed? - random

I'm looking for a code that would let me send an random embed that I created when someone types a command. For the moment with the code that I have, all embeds are being sent but I want the bot to only send a random one, not all 4. Is this possible ?
module.exports = class PizzaTest extends BaseCommand {
constructor() {
super('pizzatest', 'fun', []);
}
async run(client, message, args) {
const capreseEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Caprese** ! \n\n *Les ingrédients sont: Mozarella, Olives, Tomates Séchées & Basilic.*`)
.setThumbnail('https://i.imgur.com/McSXASC.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58");
const reineEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Reine** ! \n\n *Les ingrédients sont: Mozarella, Jambon, Champignons & Basilic.*`)
.setThumbnail('https://i.imgur.com/AKStODY.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58");
const vegeEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Végétarienne** ! \n\n *Les ingrédients sont: Mozarella, Olives, Poivrons, Champignons & Basilic.*`)
.setThumbnail('https://i.imgur.com/U0qrSk9.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58");
const andalouseEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Andalouse** ! \n\n *Les ingrédients sont: Mozarella, Poivrons, Boulette de Boeuf & Sauce Andalouse.*`)
.setThumbnail('https://i.imgur.com/dvgkC4K.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58");
message.channel.send(capreseEmbed).catch(err => console.log(err));
message.channel.send(reineEmbed).catch(err => console.log(err));
message.channel.send(vegeEmbed).catch(err => console.log(err));
message.channel.send(andalouseEmbed).catch(err => console.log(err));
}
}
I know that I can use something like .setDescription(description) with all of them stated at the beginning but I need the description and thumbnail to match so that wouldn't work I guess ?
Thank you!

Here's an easy way:
const Thumbnail = [
'https://i.imgur.com/McSXASC.png',
'https://i.imgur.com/AKStODY.png',
'https://i.imgur.com/U0qrSk9.png',
'https://i.imgur.com/dvgkC4K.png',
]
const Description = [
', il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Caprese** ! \n\n *Les ingrédients sont: Mozarella, Olives, Tomates Séchées & Basilic.*`',
', il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Végétarienne** ! \n\n *Les ingrédients sont: Mozarella, Olives, Poivrons, Champignons & Basilic.*`',
', il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Végétarienne** ! \n\n *Les ingrédients sont: Mozarella, Olives, Poivrons, Champignons & Basilic.*`',
', il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Andalouse** ! \n\n *Les ingrédients sont: Mozarella, Poivrons, Boulette de Boeuf & Sauce Andalouse.*`',
]
let random = Math.floor(Math.random() * Thumbnail.length)
const embed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription( '`' + message.author.username + Description[random])
.setThumbnail(Thumbnail[random])
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58")
message.channel.send(embed)

Yes this is possible and very simple to do:
const capreseEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Caprese** ! \n\n *Les ingrédients sont: Mozarella, Olives, Tomates Séchées & Basilic.*`)
.setThumbnail('https://i.imgur.com/McSXASC.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58")
const reineEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Reine** ! \n\n *Les ingrédients sont: Mozarella, Jambon, Champignons & Basilic.*`)
.setThumbnail('https://i.imgur.com/AKStODY.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58")
const vegeEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Végétarienne** ! \n\n *Les ingrédients sont: Mozarella, Olives, Poivrons, Champignons & Basilic.*`)
.setThumbnail('https://i.imgur.com/U0qrSk9.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58")
const andalouseEmbed = new Discord.MessageEmbed()
.setTitle('• Attention, pizza en livraison! 🚀')
.setDescription(`<#${message.author.id}>, il semblerait que ta commande soit prête. Tu viens de recevoir une magnique pizza **Andalouse** ! \n\n *Les ingrédients sont: Mozarella, Poivrons, Boulette de Boeuf & Sauce Andalouse.*`)
.setThumbnail('https://i.imgur.com/dvgkC4K.png')
.setFooter(message.author.username, message.author.displayAvatarURL())
.setTimestamp()
.setColor("#baff58")
var embedArr = [capreseEmbed, reineEmbed, vegeEmbed, andalouseEmbed];
let randomEmbed = embedArr[Math.floor(Math.random() * embedArr.length)];
message.channel.send(randomEmbed);
At first we define all embeds, like you already did. Then we store them in an array. From that array we want to get a value from a random index. That is done in randomEmbed. Then we send the random embed into the channel.

Related

I get an error when I host my discord.py bot on replit

When I host locally it works but when I host on replit it gives me this error. Initially I thought it was due to the server part I created via this video but the error comes directly from the main bot. What could be the problem?
Hosting a free bot has become quite a challenge lately. Why should I spend money on vps if my project is small?
error
Traceback (most recent call last):
File "main.py", line 401, in <module>
client.run(TOKENS)
File "/home/runner/PeppeBOT/venv/lib/python3.10/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/runner/PeppeBOT/venv/lib/python3.10/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/PeppeBOT/venv/lib/python3.10/site-packages/discord/client.py", line 745, in start
await self.login(token)
File "/home/runner/PeppeBOT/venv/lib/python3.10/site-packages/discord/client.py", line 580, in login
data = await self.http.static_login(token)
File "/home/runner/PeppeBOT/venv/lib/python3.10/site-packages/discord/http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "/home/runner/PeppeBOT/venv/lib/python3.10/site-packages/discord/http.py", line 680, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): <!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en-US"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie7 oldie" lang="en-US"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8 oldie" lang="en-US"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]-->
<head>
<title>Access denied | discord.com used Cloudflare to restrict access</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" id="cf_styles-css" href="/cdn-cgi/styles/main.css" />
<script>
(function(){if(document.addEventListener&&window.XMLHttpRequest&&JSON&&JSON.stringify){var e=function(a){var c=document.getElementById("error-feedback-survey"),d=document.getElementById("error-feedback-success"),b=new XMLHttpRequest;a={event:"feedback clicked",properties:{errorCode:1015,helpful:a,version:1}};b.open("POST","https://sparrow.cloudflare.com/api/v1/event");b.setRequestHeader("Content-Type","application/json");b.setRequestHeader("Sparrow-Source-Key","c771f0e4b54944bebf4261d44bd79a1e");
b.send(JSON.stringify(a));c.classList.add("feedback-hidden");d.classList.remove("feedback-hidden")};document.addEventListener("DOMContentLoaded",function(){var a=document.getElementById("error-feedback"),c=document.getElementById("feedback-button-yes"),d=document.getElementById("feedback-button-no");"classList"in a&&(a.classList.remove("feedback-hidden"),c.addEventListener("click",function(){e(!0)}),d.addEventListener("click",function(){e(!1)}))})}})();
</script>
<script defer src="https://performance.radar.cloudflare.com/beacon.js"></script>
</head>
<body>
<div id="cf-wrapper">
<div class="cf-alert cf-alert-error cf-cookie-error hidden" id="cookie-alert" data-translate="enable_cookies">Please enable cookies.</div>
<div id="cf-error-details" class="p-0">
<header class="mx-auto pt-10 lg:pt-6 lg:px-8 w-240 lg:w-full mb-15 antialiased">
<h1 class="inline-block md:block mr-2 md:mb-2 font-light text-60 md:text-3xl text-black-dark leading-tight">
<span data-translate="error">Error</span>
<span>1015</span>
</h1>
<span class="inline-block md:block heading-ray-id font-mono text-15 lg:text-sm lg:leading-relaxed">Ray ID: 795444d5a895b0c3 •</span>
<span class="inline-block md:block heading-ray-id font-mono text-15 lg:text-sm lg:leading-relaxed">2023-02-06 13:35:25 UTC</span>
<h2 class="text-gray-600 leading-1.3 text-3xl lg:text-2xl font-light">You are being rate limited</h2>
</header>
<section class="w-240 lg:w-full mx-auto mb-8 lg:px-8">
<div id="what-happened-section" class="w-1/2 md:w-full">
<h2 class="text-3xl leading-tight font-normal mb-4 text-black-dark antialiased" data-translate="what_happened">What happened?</h2>
<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>
</div>
</section>
<div class="feedback-hidden py-8 text-center" id="error-feedback">
<div id="error-feedback-survey" class="footer-line-wrapper">
Was this page helpful?
<button class="border border-solid bg-white cf-button cursor-pointer ml-4 px-4 py-2 rounded" id="feedback-button-yes" type="button">Yes</button>
<button class="border border-solid bg-white cf-button cursor-pointer ml-4 px-4 py-2 rounded" id="feedback-button-no" type="button">No</button>
</div>
<div class="feedback-success feedback-hidden" id="error-feedback-success">
Thank you for your feedback!
</div>
</div>
<div class="cf-error-footer cf-wrapper w-240 lg:w-full py-10 sm:py-4 sm:px-8 mx-auto text-center sm:text-left border-solid border-0 border-t border-gray-300">
<p class="text-13">
<span class="cf-footer-item sm:block sm:mb-1">Cloudflare Ray ID: <strong class="font-semibold">795444d5a895b0c3</strong></span>
<span class="cf-footer-separator sm:hidden">•</span>
<span id="cf-footer-item-ip" class="cf-footer-item hidden sm:block sm:mb-1">
Your IP:
<button type="button" id="cf-footer-ip-reveal" class="cf-footer-ip-reveal-btn">Click to reveal</button>
<span class="hidden" id="cf-footer-ip">34.74.131.130</span>
<span class="cf-footer-separator sm:hidden">•</span>
</span>
<span class="cf-footer-item sm:block sm:mb-1"><span>Performance & security by</span> <a rel="noopener noreferrer" href="https://www.cloudflare.com/5xx-error-landing" id="brand_link" target="_blank">Cloudflare</a></span>
</p>
<script>(function(){function d(){var b=a.getElementById("cf-footer-item-ip"),c=a.getElementById("cf-footer-ip-reveal");b&&"classList"in b&&(b.classList.remove("hidden"),c.addEventListener("click",function(){c.classList.add("hidden");a.getElementById("cf-footer-ip").classList.remove("hidden")}))}var a=document;document.addEventListener&&a.addEventListener("DOMContentLoaded",d)})();</script>
</div><!-- /.error-footer -->
</div><!-- /#cf-error-details -->
</div><!-- /#cf-wrapper -->
<script>
window._cf_translation = {};
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'795444d5a895b0c3',m:'Dd87hwfU_SGSbuhSCmEIgD4OJgNU9bZXc65YvwTsSWk-1675690525-0-Af7JL6WCgpne12E1VutyYAlLnWrvoh/+MVaM+Dch+KEt5KTJYCZEFTRYzIAIqarUap1plo8VlvVhzUe1OB/Hw0FA7SealXU/Uq/+mAJjPxLFRi9lCCCmdMNpckywRQaZz7LVgUU9VefBQqqQ2Il04v0=',s:[0x33c1ad0932,0xfae449c46d],u:'/cdn-cgi/challenge-platform/h/b'};var _cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/h/b/scripts/cb/invisible.js?cb=795444d5a895b0c3',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.nonce = '';_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
discord bot code
import discord
from discord import client
from discord import app_commands
from webserver import keep_alive
import datetime
import asyncio
import os
print("PeppeBOT si sta avviando...")
class VerifySelectMenuTipologia(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Giocatore", description="Se vuoi partecipare ai nostri tornei!"),
discord.SelectOption(label="Spettatore", description="Se vuoi solo assistere ai nostri tornei!")
]
super().__init__(placeholder="Seleziona la tua tipologia:",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "Giocatore":
self.spettatore = 918003194519511060
spettatore = interaction.guild.get_role(self.spettatore)
await interaction.user.add_roles(spettatore)
self.svincolato = 917269610556968970
svincolato = interaction.guild.get_role(self.svincolato)
await interaction.user.add_roles(svincolato)
elif self.values[0] == "Spettatore":
self.spettatore = 918003193982644224
spettatore = interaction.guild.get_role(self.spettatore)
await interaction.user.add_roles(spettatore)
self.membro = 918025325538078750
membro = interaction.guild.get_role(self.membro)
await interaction.user.add_roles(membro)
self.attività = 917117040035237939
attività = interaction.guild.get_role(self.attività)
await interaction.user.add_roles(attività)
self.boh = 1058541599455465483
boh = interaction.guild.get_role(self.boh)
await interaction.user.remove_roles(boh)
await interaction.delete_original_response()
class VerifySelectMenuTipologiaView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
self.add_item(VerifySelectMenuTipologia())
class VerifySelectMenuFasciaEta(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="18+", description="Se sei maggiorenne!"),
discord.SelectOption(label="14-17", description="Se sei tra i 14 e i 17 anni!"),
discord.SelectOption(label="13-",description="Se hai meno di 14 anni!")
]
super().__init__(placeholder="Seleziona la tua fascia d'età",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "18+":
self.maggiorenne = 1071955516252758167
maggiorenne = interaction.guild.get_role(self.maggiorenne)
await interaction.user.add_roles(maggiorenne)
await interaction.response.edit_message(content="Manca solo l'ultima selezione! Sei un giocatore o uno spettatore?", view=VerifySelectMenuTipologiaView())
elif self.values[0] == "14-17":
self.mezzo = 1071955345532014652
mezzo = interaction.guild.get_role(self.mezzo)
await interaction.user.add_roles(mezzo)
await interaction.response.edit_message(content="Manca solo l'ultima selezione! Sei un giocatore o uno spettatore?", view=VerifySelectMenuTipologiaView())
elif self.values[0] == "13-":
self.minorenne = 1071955284534247534
minorenne = interaction.guild.get_role(self.minorenne)
await interaction.user.add_roles(minorenne)
await interaction.response.edit_message(content="Manca solo l'ultima selezione! Sei un giocatore o uno spettatore?", view=VerifySelectMenuTipologiaView())
class VerifySelectMenuFasciaEtaView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
self.add_item(VerifySelectMenuFasciaEta())
class VerifyModal(discord.ui.Modal, title='Verifica'):
nickname = discord.ui.TextInput(
label="Nickname di haxball:",
placeholder="Scrivi qui il tuo nickname di haxball (ricorda non potrai più cambiarlo)",
min_length=1,
max_length=10,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.user.edit(nick= f'{self.nickname}')
await interaction.response.send_message(content="Ottimo! Ora seleziona la tua fascia d'età", view=VerifySelectMenuFasciaEtaView(), ephemeral=True)
class VerifyButton(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
#discord.ui.button(label="Verificati", style=discord.ButtonStyle.green, custom_id="verify_button")
async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
if type(client.role) is not discord.Role: client.role = interaction.guild.get_role(918025325538078750)
if client.role not in interaction.user.roles:
modal = VerifyModal()
await interaction.response.send_modal(modal)
else:
await interaction.response.send_message("Sei già verificato!", ephemeral=True, delete_after=10)
class PersistentViewBot(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.all())
self.synced = False
self.added = False
self.role = 918025325538078750
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=917112143420215338))
self.synced = True
if not self.added:
self.add_view(VerifyButton())
self.added = True
print(self.user, " si è avviato!")
print("ID :", self.user.id)
global logs_moderazione
global logs_generali
logs_moderazione = self.get_channel(917274076962258975)
logs_generali = self.get_channel(917274597466972230)
embed = discord.Embed(
color=0x03c03c
)
embed.set_author(
name=f'Avvio/Riavvio del Bot!',
)
await tree.sync(guild=discord.Object(id=1006702784797749288))
await logs_moderazione.send(embed=embed)
await tree.sync(guild=discord.Object(id=guild_id))
client = PersistentViewBot()
tree = app_commands.CommandTree(client)
guild_id = 917112143420215338
#client.event
async def on_member_join(member):
guild = member.guild
firstrole = guild.get_role(1058541599455465483)
await member.add_roles(firstrole)
tab1 = guild.get_role(918002005040046100)
await member.add_roles(tab1)
tab2 = guild.get_role(918003746850623529)
await member.add_roles(tab2)
tab3 = guild.get_role(918003750944272425)
await member.add_roles(tab3)
tab4 = guild.get_role(917119249145798716)
await member.add_roles(tab4)
mention = member.mention
guild_id = member.guild
member_count = guild_id.member_count
embed = discord.Embed(
description=str(f"{mention} è entrato su **{guild}!**\nIn tutto ora ci sono **{member_count}** membri."),
color=0x222222
)
await logs_generali.send(embed=embed)
#client.event
async def on_member_remove(member):
name = member.mention
guild = member.guild
member_count = guild.member_count
embed = discord.Embed(
description=str(str(f"**{name}** è uscito da **{guild}!**\nIn tutto ora ci sono **{member_count}** membri.")),
color=0x222222
)
await logs_generali.send(embed=embed)
#Comandi di Moderazione
#Clear [COMPLETO]
clear_cooldown = app_commands.Cooldown(1,600)
def clear_cooldown_checker(interaction: discord.Interaction):
return clear_cooldown
#app_commands.checks.dynamic_cooldown(clear_cooldown_checker, key=lambda i: (i.user.id))
#tree.command(name = "clear", description = "Cancella gli ultimi messaggi inviati ", guild=discord.Object(id=guild_id))
async def clear(ctx, limit: int):
await ctx.response.defer(ephemeral=False, thinking=False)
embed = discord.Embed(
color=0xa61022
)
if limit == 0:
embed.set_author(
name="Non puoi cancellare 0 messaggi!",
)
await ctx.response.send_message(embed=embed, delete_after=10.0)
app_commands.Cooldown.reset(clear_cooldown)
embed = discord.Embed(
color=0x03c03c
)
if limit == 1:
embed.set_author(
name=f'Ho cancellato ufficialmente un messaggio!',
icon_url=f'{ctx.user.avatar}'
)
else:
embed.set_author(
name=f'Ho cancellato ufficialmente {limit} messaggi!',
icon_url=f'{ctx.user.avatar}'
)
await ctx.channel.purge(limit=limit, before=ctx.created_at)
await ctx.followup.send(embed=embed)
embed = discord.Embed(
color=0xFFD000
)
if limit == 1:
embed.set_author(
name=f'{ctx.user.name} ha cancellato un messaggio',
icon_url=f'{ctx.user.avatar}'
)
else:
embed.set_author(
name=f'{ctx.user.name} ha cancellato {limit} messaggi',
icon_url=f'{ctx.user.avatar}'
)
embed.add_field(
name='Messaggi cancellati da:',
value=f'{ctx.user.name}',
inline=True
)
embed.add_field(
name='Quantità:',
value=f'{limit}',
inline=True
)
embed.add_field(
name='Canale dove è stato eseguito il comando:',
value=f'{ctx.channel.mention}',
inline=True
)
await logs_moderazione.send(embed=embed)
await asyncio.sleep(10)
await ctx.delete_original_response()
#clear.error
async def clear_error(ctx, error):
await ctx.response.defer(ephemeral=False, thinking=False)
if isinstance(error, app_commands.CommandOnCooldown):
cooldown = error.cooldown
cd = round(cooldown.get_retry_after())
time = str(datetime.timedelta(seconds=cd))
embed = discord.Embed(
description=f"**Riprova tra `{time}`**",
color=0xa61022
)
embed.set_author(
name="Sei in cooldown!",
icon_url=ctx.user.avatar
)
await ctx.followup.send(embed=embed)
await asyncio.sleep(10)
await ctx.delete_original_response()
#acclear [COMPLETO]
#tree.command(name = "acclear", description = "Cancella con accuratezza gli ultimi messaggi inviati ", guild=discord.Object(id=guild_id))
async def acclear(ctx, message_id: str):
await ctx.response.defer(ephemeral=False, thinking=False)
embed = discord.Embed(
color=0xa61022
)
def message_limit(m):
messageID = message.id
return m.id != messageID
channel = ctx.channel
try:
message = await channel.fetch_message(message_id)
except:
embed.set_author(
name="Non ho trovato il messaggio!",
icon_url=ctx.user.avatar
)
await ctx.response.send_message(embed=embed, delete_after=10.0)
await asyncio.sleep(10)
return 0
embed = discord.Embed(
color=0x03c03c
)
embed.set_author(
name=f'Ho cancellato fino al messaggio:\n{message.content}',
icon_url=f'{ctx.user.avatar}'
)
await ctx.channel.purge(limit=10000, before=ctx.created_at, check=message_limit, after=message)
if message.content == "":
await ctx.followup.send(embed=embed)
embed = discord.Embed(
color=0xFFD000
)
embed.set_author(
name=f'{ctx.user.name} ha cancellato fino al messaggio:\nNon ha testo',
icon_url=f'{ctx.user.avatar}'
)
embed.add_field(
name='Messaggi cancellati da:',
value=f'{ctx.user.name}',
inline=True
)
embed.add_field(
name='Fino al messaggio:',
value=f'Non ha testo',
inline=True
)
embed.add_field(
name='Canale dove è stato eseguito il comando:',
value=f'{ctx.channel.mention}',
inline=True
)
await logs_moderazione.send(embed=embed)
await asyncio.sleep(10)
await ctx.delete_original_response()
else:
await ctx.followup.send(embed=embed)
embed = discord.Embed(
color=0xFFD000
)
embed.set_author(
name=f'{ctx.user.name} ha cancellato fino al messaggio:\n{message.content}',
icon_url=f'{ctx.user.avatar}'
)
embed.add_field(
name='Messaggi cancellati da:',
value=f'{ctx.user.name}',
inline=True
)
embed.add_field(
name='Fino al messaggio:',
value=f'{message.content}',
inline=True
)
embed.add_field(
name='Canale dove è stato eseguito il comando:',
value=f'{ctx.channel.mention}',
inline=True
)
await logs_moderazione.send(embed=embed)
await asyncio.sleep(10)
await ctx.delete_original_response()
#tree.command(name = 'verifybutton', description='Crea il bottone per verificarsi', guild=discord.Object(id=guild_id))
async def verifybutton(ctx):
embed = discord.Embed(
description=str("Benvenuto nel server, prima di poter accedere a tutti i canali è importante verificarsi rispondendo a delle domande molto semplici ossia."),
color=0x222222
)
embed.set_author(
name='PeppeBOT',
icon_url=f'{client.user.avatar}'
)
embed.set_footer(text=f'Haxball Biglassic')
embed.add_field(
name='Domande:',
value="1.Qual è il tuo nickname di haxball?\n2.Qual è la tua fascia d'età?\n3.Sei uno spettatore o un giocatore?",
inline=False
)
embed.add_field(
name='Come rispondere alle domande:',
value="Nella prima domanda dovrai decidere quale nick di haxball utilizzare per questo server senza poterlo cambiare in futuro (ovviamente con le sue regole).\nNella seconda domanda dovrai specificare la tua fascia d'età tra:\n**1.** 13-\n**2.** 14-17\n**3.** 18+\nNella terza domanda dovrai semplicemente dirci se sei venuto per giocare ai tornei organizzati da noi (e quindi essere un effettivo giocatore) oppure se sei venuto semplicemente per conversare e guardare le partite del torneo da spettatore.",
inline=False
)
await ctx.channel.send(embed = embed, view = VerifyButton())
await ctx.response.send_message(content="** **", delete_after=0.1)
sesso_cooldown = app_commands.Cooldown(1,10)
def sesso_cooldown_checker(interaction: discord.Interaction):
return sesso_cooldown
#app_commands.checks.dynamic_cooldown(sesso_cooldown_checker, key=lambda i: (i.user.id))
#tree.command(name = "sesso", description = "Cancella gli ultimi messaggi inviati ", guild=discord.Object(id=guild_id))
async def sesso(ctx):
print(sesso_cooldown)
await ctx.response.send_message("andrea")
await ctx.edit_original_response(content="andrea2")
app_commands.Cooldown.reset(sesso_cooldown)
#sesso.error
async def sesso_error(ctx, error):
if isinstance(error, app_commands.CommandOnCooldown):
cooldown = error.cooldown
cd = round(cooldown.get_retry_after())
time = str(datetime.timedelta(seconds=cd))
embed = discord.Embed(
description=f"**Riprova tra `{time}`**",
color=0xa61022
)
embed.set_author(
name=f"Sei in cooldown!",
icon_url=ctx.user.avatar
)
await ctx.response.send_message(embed=embed)
for i in range(10):
await asyncio.sleep(1)
cd = round(cooldown.get_retry_after())
time = str(datetime.timedelta(seconds=cd))
embed = discord.Embed(
description=f"**Riprova tra `{time}`**",
color=0xa61022
)
embed.set_author(
name=f"Sei in cooldown!",
icon_url=ctx.user.avatar
)
await ctx.edit_original_response(embed=embed)
keep_alive()
TOKENS = os.environ['SECRET_DISCORD_TOKENS']
client.run(TOKENS)
webserver
from flask import Flask
from threading import Thread
app = Flask('')
#app.route("/")
def home():
return "sono vivo"
def run():
app.run(host= '0.0.0.0', port= 8080)
def keep_alive():
t = Thread(target=run)
t.start()
This error occurs when your bot has sent too many requests in a short amount of time. To resolve this, type kill 1 in the shell (located in the bottom window of the Replit IDE) and hit enter. This will halt your bot's processes and reset its connection. Remember to rerun the bot to reconnect.

Laravel Route not defined when it is

I have this error.
And this simple code
<div class="copyright">
<a href="/" id="footer-logo"><img src="/img/footer-logo.png"
alt="Avel Developpement, votre toute nouvelle agence web spécialisée dans la création d'applications web et mobile dans la Loire. "></a>
| © {{now()->year}} | Mentions Légales - Données personnelles
</div>
and
Route::get('/', function () {
return view('home');
});
Route::get('/mentions-legales', function () {
return view('mentions');
})->name('mentions');
Route::get('/donnees-perso', function () {
return view('donnees-perso');
})->name('donnees-perso');
I don't understand what is my mistake

Skrollr - how to permit the scroll of a long text of unknown size until the end

Please what is the trick so that a long text of several pages (filled for example with text "Lorem ipsum ...") of unknown length (no known in advance) become visible beyond one page which is freezes (not able to see after) because skrollr ?
My simple skrollr code that bug to scrool to the end of a long text (size not fixed) beyond one page:
<div id = "corpsDiv"
data-0 = "transform: translateY (100vh)"
data-500 = "transform: translateY (100vh)"
data-900 = "transform: translateY (0vh)">
Lorem ipsum dolor sit amet. <BR>
Qui cupiditate nisi est praesentium omnis et reprehenderit veniam <BR>
Est dolor perspiciatis ea placeat quaerat <BR>
et galisum provident aut cumque iste sed reiciendis esse <BR>
... etc <BR>
</div>
As no one answered, I share with you the solution that I found to help others :
<script type="text/javascript">
/* function : recalculSkrollr()
=== Création dynamique du dernier attribut skrollr positionnant la fin du div de texte Corps de page pour pouvoir la scroller
Nota : comme le div de texte ci-dessus "corpsDiv" est dynamique (ie de hauteur inconnue à l'avance selon le contenu et la taille d'écran),
et que skrollr ne sait donc pas afficher toute sa hauteur (ne connaissant pas sa valeur non figée no plus arbitrairement par le css),
alors seule la première page de ce div de texte (positionné à 0vh par skrollr via data-0) sera visible,
sans pouvoir la scroller tant qu'un attribut skrollr, indiquant jusqu'où scroller, ne sera pas créé pour voir l'intégralité de ce div,
soit tant qu'un attribut skrollr data-{hauteur_px_du_div} indiquant une valeur égale de translation Y négative (vers le haut)
de {hauteur_vh_du_div} (vh pour être homogène avec les autres unités vh des data skrollr du div) ne sera pas dynamiquement créé,
ce qui est fait (nécessairement après ce div) ici à la fin de cette page.
*/
function recalculSkrollr() {
// Calcul du viewport height en cours (via la taille de l'écran)
screenHeight= window.innerHeight || (document.body && document.body.clientHeight) || 800;
viewHeight = screenHeight / 100; // View port (1% de la hauteur d'écran)
// Calcul hauteur du div en px (taille du div inconnue à l'avance) afin de pouvoir le scroller (ici scrollTop=0 car div par encore au-dessus du top à 0)
vcorpsDiv = document.getElementById('corpsDiv');
hauteurPxCorpsDiv = vcorpsDiv.offsetHeight;
// Garder une hauteur minimum (150 vh) pour afficher correctement un corpsDiv qui serait trop petit (skrollr perturbé sinon)
hauteurPxCorpsDiv = Math.max(hauteurPxCorpsDiv , 150 * viewHeight);
// Calcul hauteur du div (en vh) pour permettre à skrollr de translater le div vers le haut
hauteurVhCorpsDiv = Math.trunc(hauteurPxCorpsDiv / viewHeight);
// Calcul du décalage du div (en vh) vers le haut une fois entièrement scrollé (en soustrayant l'offset déjà appliqué dans la déclaration html du corpsDiv via son attribut skrollr data-0="transform:translateY(100vh)")
offsetVhCorpsDiv = 100;
decaleVhCorpsDiv = hauteurVhCorpsDiv - offsetVhCorpsDiv;
// Calcul de l'attribut skrollr (libellé et valeur du tag) à créer dynamiquement afin de pouvoir scroller entièrement le div
csstag='data-'+hauteurPxCorpsDiv;
cssvalue='transform:translateY(-'+decaleVhCorpsDiv+'vh)'; // pas besoin à priori des accolades css : cssvalue = '{' + cssvalue + '}'
// Création de l'attibut skrollr permettant de scroller le div jusqu'au bout
document.getElementById('corpsDiv').setAttribute(csstag, cssvalue);
// Création de l'attibut height du div
cssheight = hauteurVhCorpsDiv + 'vh';
document.getElementById('corpsDiv').style.height = cssheight;
}
recalculSkrollr();
// Décaler dans le temps (500ms) l'init du scroll pour laisser le temps à la page de se charger (sinon le scrollr.menu avec une url #xxx restera en haut)
setTimeout(function() {
/* ==== Initialisation du gestionnaire skrollr (voir source et doc https://prinzhorn.github.io/skrollr/ ) */
var skroller = skrollr.init({
constants: {
// Position vertical avant et après l'ouverture du portail (en px) pour l'animer dans l'image d'entete
avantportail: function() {
// Calcul d'une constante dynamique (possible aussi d'accéder à l'instance skrollr avec `this` par ex. `this.relativeToAbsolute`)
positionVhCible = 50; // position cible à atteindre en unité vh (1/100 du viewport height)
positionPxCible = positionVhCible * viewHeight;
return positionPxCible;
},
apresportail: function() {
positionVhCible = 140; // position cible à atteindre en vh
positionPxCible = positionVhCible * viewHeight;
return positionPxCible;
}
}
});
//The options (second parameter) are all optional. The values shown are the default values.
skrollr.menu.init(skroller, {
//skrollr will smoothly animate to the new position using `animateTo`.
animate: true,
//The easing function to use.
easing: 'sqrt',
//Multiply your data-[offset] values so they match those set in skrollr.init
scale: 1,
//This event is triggered right before we jump/animate to a new hash.
change: function(newHash, newTopPosition) {
//console.log(hash, top);
}
});
}, 500);
// Recharger la page si la page change de taille afin de recalculer les attributs dynamiques de skrollr
function pageResize() {
document.location.reload();
}
window.onresize = pageResize;
</script>

Power Query does not stop loading lines after table ended

Well, my problem is basically what the title says: I have a table that retrieves data from a table in another excel file, and now, doesn't stop loading lines, well after said table ended.
The script that I have (see bellow), has another table innerjoined, but that table, also from PowerQuery, that retrieves a table from yet another excel file, loads just fine. No problems. The main one is the one that does not stop until like 3000000 lines (original table is 3000 lines).
I can't understand the problem, because this has been working just fine.
let
Origem = Excel.Workbook(File.Contents("\\SERVIDOR\Registo de defeitos\REGISTO_DEFEITOS_2016.xlsm"), null, true),
REGISTRY_Table = Origem{[Item="REGISTRY",Kind="Table"]}[Data],
#"Tipo Alterado" = Table.TransformColumnTypes(REGISTRY_Table,{{"FINDER", type text}, {"DATA", type date}, {"ORDEM FABRICO", Int64.Type}, {"REFERÊNCIA", Int64.Type}, {"LOTE", type text}, {"OPERADOR", type text}, {"PRENSA", Int64.Type}, {"TURNO", Int64.Type}, {"PRODUÇÃO TOTAL#(lf)(Nº DE PEÇAS)", Int64.Type}, {"A", Int64.Type}, {"B", Int64.Type}, {"C", Int64.Type}, {"D", Int64.Type}, {"E", Int64.Type}, {"F", Int64.Type}, {"Z", Int64.Type}, {"L", Int64.Type}, {"M", Int64.Type}, {"N", Int64.Type}, {"O", Int64.Type}, {"P", Int64.Type}, {"QUANTIDADE DE PEÇAS OK#(lf)(PRENSA)", Int64.Type}, {"QUANTIDADE DE PEÇAS NOK#(lf)(PRENSA)", Int64.Type}, {"% DEFEITOS#(lf)(PRENSA)", type number}, {"% DETECÇÃO DE DEFEITOS#(lf)(PRENSA)", type number}, {"DATA DE INSPECÇÃO", type date}, {"QUANTIDADE DE PEÇAS VERIFICADA#(lf)(Nº DE PEÇAS)", Int64.Type}, {"TIPO DE INSPECÇÃO", type text}, {"A ", Int64.Type}, {"B ", Int64.Type}, {"C ", Int64.Type}, {"D ", Int64.Type}, {"E ", Int64.Type}, {"F ", Int64.Type}, {"Z ", Int64.Type}, {"L ", Int64.Type}, {"M ", Int64.Type}, {"N ", Int64.Type}, {"O ", Int64.Type}, {"P ", Int64.Type}, {"PEÇAS RETRABALHADAS ""OK""#(lf)(Nº DE PEÇAS)", Int64.Type}, {"LOTE#(lf)FECHADO", type text}, {"QUANTIDADE DE PEÇAS OK#(lf)(INSP. FINAL)", Int64.Type}, {"QUANTIDADE DE PEÇAS NOK#(lf)(INSP. FINAL)", Int64.Type}, {"% DEFEITOS#(lf)(INSP. FINAL)", type number}, {"QUANTIDADE DE PEÇAS OK#(lf)(FINAL)", Int64.Type}, {"QUANTIDADE DE PEÇAS NOK#(lf)(FINAL)", Int64.Type}, {"% DEFEITOS#(lf)(FINAL)", type number}, {"CONTABILIZAÇÃO DE PEÇAS", Int64.Type}, {"TESTER", Int64.Type}, {"MÊS", type text}, {"ANO", Int64.Type}, {"MÊS INSP.", type text}, {"ANO INSP.", Int64.Type}}),
#"Colunas Removidas" = Table.RemoveColumns(#"Tipo Alterado",{"TESTER"}),
#"Consultas Intercaladas" = Table.NestedJoin(#"Colunas Removidas",{"FINDER"},TabelaRegistos,{"FINDER"},"NewColumn",JoinKind.Inner),
#"Expandido NewColumn" = Table.ExpandTableColumn(#"Consultas Intercaladas", "NewColumn", {"Nº DE CAVIDADES", "PRODUÇÃO PREVISTA (nº de cargas/h)", "AJUSTE DE OBJECTIVO PRODUÇÃO PREVISTA#(lf)(nº de cargas/h)", "PRODUÇÃO TOTAL#(lf)(nº de peças)", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "Z ", "PRENSA SEM PARAGEM PARA REFEIÇÕES?", "J ", "TEMPO DE PARAGEM NÃO PROGRAMADA (min)", "TEMPO DE PARAGEM PROGRAMADA (min)", "AJUSTE DE TEMPO DE TURNO#(lf)(min)", "LOTE FECHADO", "OBSERVAÇÕES", "PRODUÇÃO EFECTIVA#(lf)(nº de cargas/h)", "PERFORMANCE#(lf)(%)", "DISPONIBILIDADE#(lf)(%)", "QUALIDADE PRENSA#(lf)(%)", "QUALIDADE#(lf)(%)", "OEE OBJECTIVO#(lf)(%)", "WE OBJECTIVO#(lf)(%)", "OEE PRENSA#(lf)(%)", "OEE#(lf)(%)", "Δ OEE#(lf)(Δ%)", "WE PRENSA#(lf)(%)", "WE#(lf)(%)", "Δ WE#(lf)(Δ%)", "TEMPO DE TRABALHO DISPONÍVEL#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS PROGRAMADAS#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS NÃO PROGRAMADAS#(lf)(min)", "TEMPO DE LABORAÇÃO EFECTIVO#(lf)(min)", "EFICÁCIA DE UTILIZAÇÃO#(lf)(%)", "FINDER", "COMMENTS", "NOME MÊS", "AProg", "BProg", "CProg", "DProg", "EProg", "FProg", "GProg", "HProg", "IProg", "Zprog", "ANProg", "BNProg", "CNProg", "DNProg", "ENProg", "FNProg", "GNProg", "HNProg", "INProg", "ZNprog"}, {"Nº DE CAVIDADES", "PRODUÇÃO PREVISTA (nº de cargas/h)", "AJUSTE DE OBJECTIVO PRODUÇÃO PREVISTA#(lf)(nº de cargas/h)", "PRODUÇÃO TOTAL#(lf)(nº de peças)", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "Z ", "PRENSA SEM PARAGEM PARA REFEIÇÕES?", "J ", "TEMPO DE PARAGEM NÃO PROGRAMADA (min)", "TEMPO DE PARAGEM PROGRAMADA (min)", "AJUSTE DE TEMPO DE TURNO#(lf)(min)", "LOTE FECHADO", "OBSERVAÇÕES", "PRODUÇÃO EFECTIVA#(lf)(nº de cargas/h)", "PERFORMANCE#(lf)(%)", "DISPONIBILIDADE#(lf)(%)", "QUALIDADE PRENSA#(lf)(%)", "QUALIDADE#(lf)(%)", "OEE OBJECTIVO#(lf)(%)", "WE OBJECTIVO#(lf)(%)", "OEE PRENSA#(lf)(%)", "OEE#(lf)(%)", "Δ OEE#(lf)(Δ%)", "WE PRENSA#(lf)(%)", "WE#(lf)(%)", "Δ WE#(lf)(Δ%)", "TEMPO DE TRABALHO DISPONÍVEL#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS PROGRAMADAS#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS NÃO PROGRAMADAS#(lf)(min)", "TEMPO DE LABORAÇÃO EFECTIVO#(lf)(min)", "EFICÁCIA DE UTILIZAÇÃO#(lf)(%)", "FINDER.1", "COMMENTS", "NOME MÊS", "AProg", "BProg", "CProg", "DProg", "EProg", "FProg", "GProg", "HProg", "IProg", "Zprog", "ANProg", "BNProg", "CNProg", "DNProg", "ENProg", "FNProg", "GNProg", "HNProg", "INProg", "ZNprog"}),
#"Colunas Removidas1" = Table.RemoveColumns(#"Expandido NewColumn",{"PRODUÇÃO TOTAL#(lf)(nº de peças)"}),
#"Personalizado Adicionado" = Table.AddColumn(#"Colunas Removidas1", "PRODUÇÃO TOTAL OBJECTIVO (Nº DE PEÇAS)", each [Nº DE CAVIDADES]*[#"PRODUÇÃO PREVISTA (nº de cargas/h)"]*[#"TEMPO DE TRABALHO COM PARAGENS NÃO PROGRAMADAS#(lf)(min)"]/60),
#"Tipo Alterado1" = Table.TransformColumnTypes(#"Personalizado Adicionado",{{"PRODUÇÃO TOTAL OBJECTIVO (Nº DE PEÇAS)", Int64.Type}}),
#"Trimestre Inserido" = Table.AddColumn(#"Tipo Alterado1", "TRIMESTRE", each Date.QuarterOfYear([DATA]), type number),
#"Personalizado Adicionado1" = Table.AddColumn(#"Trimestre Inserido", "PRODUÇÃO TOTAL OBJECTIVO (TEMPO EFECTIVO)", each [Nº DE CAVIDADES]*[#"PRODUÇÃO PREVISTA (nº de cargas/h)"]*[#"TEMPO DE LABORAÇÃO EFECTIVO#(lf)(min)"]/60),
#"Tipo Alterado2" = Table.TransformColumnTypes(#"Personalizado Adicionado1",{{"PRODUÇÃO TOTAL OBJECTIVO (TEMPO EFECTIVO)", Int64.Type}}),
#"Colunas com Nome Mudado" = Table.RenameColumns(#"Tipo Alterado2",{{"PRODUÇÃO TOTAL OBJECTIVO (Nº DE PEÇAS)", "PRODUÇÃO TOTAL OBJECTIVO (TEMPO COM PARAGENS NÃO PROGRAMADAS)"}}),
#"Colunas Reordenadas" = Table.ReorderColumns(#"Colunas com Nome Mudado",{"FINDER", "DATA", "ORDEM FABRICO", "REFERÊNCIA", "LOTE", "OPERADOR", "PRENSA", "TURNO", "PRODUÇÃO TOTAL#(lf)(Nº DE PEÇAS)", "A", "B", "C", "D", "E", "F", "Z", "L", "M", "N", "O", "P", "QUANTIDADE DE PEÇAS OK#(lf)(PRENSA)", "QUANTIDADE DE PEÇAS NOK#(lf)(PRENSA)", "% DEFEITOS#(lf)(PRENSA)", "% DETECÇÃO DE DEFEITOS#(lf)(PRENSA)", "DATA DE INSPECÇÃO", "QUANTIDADE DE PEÇAS VERIFICADA#(lf)(Nº DE PEÇAS)", "TIPO DE INSPECÇÃO", "A ", "B ", "C ", "D ", "E ", "F ", "Z ", "L ", "M ", "N ", "O ", "P ", "PEÇAS RETRABALHADAS ""OK""#(lf)(Nº DE PEÇAS)", "LOTE#(lf)FECHADO", "QUANTIDADE DE PEÇAS OK#(lf)(INSP. FINAL)", "QUANTIDADE DE PEÇAS NOK#(lf)(INSP. FINAL)", "% DEFEITOS#(lf)(INSP. FINAL)", "QUANTIDADE DE PEÇAS OK#(lf)(FINAL)", "QUANTIDADE DE PEÇAS NOK#(lf)(FINAL)", "% DEFEITOS#(lf)(FINAL)", "CONTABILIZAÇÃO DE PEÇAS", "MÊS", "ANO", "MÊS INSP.", "ANO INSP.", "Nº DE CAVIDADES", "PRODUÇÃO PREVISTA (nº de cargas/h)", "AJUSTE DE OBJECTIVO PRODUÇÃO PREVISTA#(lf)(nº de cargas/h)", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "Z ", "PRENSA SEM PARAGEM PARA REFEIÇÕES?", "J ", "TEMPO DE PARAGEM NÃO PROGRAMADA (min)", "TEMPO DE PARAGEM PROGRAMADA (min)", "AJUSTE DE TEMPO DE TURNO#(lf)(min)", "LOTE FECHADO", "OBSERVAÇÕES", "PRODUÇÃO EFECTIVA#(lf)(nº de cargas/h)", "PERFORMANCE#(lf)(%)", "DISPONIBILIDADE#(lf)(%)", "QUALIDADE PRENSA#(lf)(%)", "QUALIDADE#(lf)(%)", "OEE OBJECTIVO#(lf)(%)", "WE OBJECTIVO#(lf)(%)", "OEE PRENSA#(lf)(%)", "OEE#(lf)(%)", "Δ OEE#(lf)(Δ%)", "WE PRENSA#(lf)(%)", "WE#(lf)(%)", "Δ WE#(lf)(Δ%)", "TEMPO DE TRABALHO DISPONÍVEL#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS PROGRAMADAS#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS NÃO PROGRAMADAS#(lf)(min)", "TEMPO DE LABORAÇÃO EFECTIVO#(lf)(min)", "EFICÁCIA DE UTILIZAÇÃO#(lf)(%)", "FINDER.1", "COMMENTS", "NOME MÊS", "TRIMESTRE", "AProg", "BProg", "CProg", "DProg", "EProg", "FProg", "GProg", "HProg", "IProg", "Zprog", "ANProg", "BNProg", "CNProg", "DNProg", "ENProg", "FNProg", "GNProg", "HNProg", "INProg", "ZNprog", "PRODUÇÃO TOTAL OBJECTIVO (TEMPO COM PARAGENS NÃO PROGRAMADAS)", "PRODUÇÃO TOTAL OBJECTIVO (TEMPO EFECTIVO)"}),
#"Colunas Removidas2" = Table.RemoveColumns(#"Colunas Reordenadas",{"FINDER.1", "FINDER"}),
#"Personalizado Adicionado2" = Table.AddColumn(#"Colunas Removidas2", "PERFORMANCE LÍQUIDA (%)", each [#"QUANTIDADE DE PEÇAS OK#(lf)(FINAL)"]/[#"PRODUÇÃO TOTAL OBJECTIVO (TEMPO EFECTIVO)"]),
#"Colunas Removidas3" = Table.RemoveColumns(#"Personalizado Adicionado2",{"NOME MÊS"}),
#"Colunas Reordenadas1" = Table.ReorderColumns(#"Colunas Removidas3",{"DATA", "ORDEM FABRICO", "REFERÊNCIA", "LOTE", "OPERADOR", "PRENSA", "TURNO", "PRODUÇÃO TOTAL#(lf)(Nº DE PEÇAS)", "A", "B", "C", "D", "E", "F", "Z", "L", "M", "N", "O", "P", "QUANTIDADE DE PEÇAS OK#(lf)(PRENSA)", "QUANTIDADE DE PEÇAS NOK#(lf)(PRENSA)", "% DEFEITOS#(lf)(PRENSA)", "% DETECÇÃO DE DEFEITOS#(lf)(PRENSA)", "DATA DE INSPECÇÃO", "QUANTIDADE DE PEÇAS VERIFICADA#(lf)(Nº DE PEÇAS)", "TIPO DE INSPECÇÃO", "A ", "B ", "C ", "D ", "E ", "F ", "Z ", "L ", "M ", "N ", "O ", "P ", "PEÇAS RETRABALHADAS ""OK""#(lf)(Nº DE PEÇAS)", "LOTE#(lf)FECHADO", "QUANTIDADE DE PEÇAS OK#(lf)(INSP. FINAL)", "QUANTIDADE DE PEÇAS NOK#(lf)(INSP. FINAL)", "% DEFEITOS#(lf)(INSP. FINAL)", "QUANTIDADE DE PEÇAS OK#(lf)(FINAL)", "QUANTIDADE DE PEÇAS NOK#(lf)(FINAL)", "% DEFEITOS#(lf)(FINAL)", "CONTABILIZAÇÃO DE PEÇAS", "MÊS", "TRIMESTRE", "ANO", "MÊS INSP.", "ANO INSP.", "Nº DE CAVIDADES", "PRODUÇÃO PREVISTA (nº de cargas/h)", "AJUSTE DE OBJECTIVO PRODUÇÃO PREVISTA#(lf)(nº de cargas/h)", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "Z ", "PRENSA SEM PARAGEM PARA REFEIÇÕES?", "J ", "TEMPO DE PARAGEM NÃO PROGRAMADA (min)", "TEMPO DE PARAGEM PROGRAMADA (min)", "AJUSTE DE TEMPO DE TURNO#(lf)(min)", "LOTE FECHADO", "OBSERVAÇÕES", "PRODUÇÃO EFECTIVA#(lf)(nº de cargas/h)", "PERFORMANCE#(lf)(%)", "DISPONIBILIDADE#(lf)(%)", "QUALIDADE PRENSA#(lf)(%)", "QUALIDADE#(lf)(%)", "OEE OBJECTIVO#(lf)(%)", "WE OBJECTIVO#(lf)(%)", "OEE PRENSA#(lf)(%)", "OEE#(lf)(%)", "Δ OEE#(lf)(Δ%)", "WE PRENSA#(lf)(%)", "WE#(lf)(%)", "Δ WE#(lf)(Δ%)", "TEMPO DE TRABALHO DISPONÍVEL#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS PROGRAMADAS#(lf)(min)", "TEMPO DE TRABALHO COM PARAGENS NÃO PROGRAMADAS#(lf)(min)", "TEMPO DE LABORAÇÃO EFECTIVO#(lf)(min)", "EFICÁCIA DE UTILIZAÇÃO#(lf)(%)", "COMMENTS", "AProg", "BProg", "CProg", "DProg", "EProg", "FProg", "GProg", "HProg", "IProg", "Zprog", "ANProg", "BNProg", "CNProg", "DNProg", "ENProg", "FNProg", "GNProg", "HNProg", "INProg", "ZNprog", "PRODUÇÃO TOTAL OBJECTIVO (TEMPO COM PARAGENS NÃO PROGRAMADAS)", "PRODUÇÃO TOTAL OBJECTIVO (TEMPO EFECTIVO)", "PERFORMANCE LÍQUIDA (%)"}),
#"Personalizado Adicionado3" = Table.AddColumn(#"Colunas Reordenadas1", "100%", each 1),
#"Personalizado Adicionado4" = Table.AddColumn(#"Personalizado Adicionado3", "90%", each 0.9),
#"Personalizado Adicionado5" = Table.AddColumn(#"Personalizado Adicionado4", "85%", each 0.85),
#"Personalizado Adicionado6" = Table.AddColumn(#"Personalizado Adicionado5", "80%", each 0.80),
#"Personalizado Adicionado7" = Table.AddColumn(#"Personalizado Adicionado6", "70%", each 0.70),
#"Personalizado Adicionado8" = Table.AddColumn(#"Personalizado Adicionado7", "60%", each 0.60),
#"Personalizado Adicionado9" = Table.AddColumn(#"Personalizado Adicionado8", "50%", each 0.50)
in
#"Personalizado Adicionado9"
Thanks to all that can help.
Possibly something is wrong with your key values:
1 Excel table can not have 3 million lines as the maximum is just over 1 million, so logically the source of your issue is at the step where the nested table is expanded: #"Expandido NewColumn".
I ran a small test with 2 tables, each with keys 1-10 and an inner join resulting in a table with 10 rows. So far so good.
Next I emptied the contents of the key columns of each table and ran the query again, resulting in 10 x 10 = 100 rows as each key in either table corresponds with 10 keys in the other table.
So my suggestion would be to verify the values in your FINDER columns.
If this is not the cause, then please share: which is the first step that is causing the issue: you can check each step in the Query Editor.

$.ajax statusCode function never receive parameters

According to the official jQuery doc :
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
But in fact, it's not. With this code :
function saveCampagne (data){
$.ajax({
url : url,
type : "GET",
data : data,
statusCode:{
201 : function(campagne){
// JSON Decode
var Campagne = JSON.parse(campagne);
$("#zone-message").append('<div class="alert fade in" data-alert="alert"><a class="close" data-dismiss="alert" href="#">×</a><p><strong>C\'est Fait !</strong> La campagne a été ajoutée sous la référence #'+Campagne.id+'. Elle sera validée prochainement par un administrateur.</p></div>');
return Campagne;
},
200 : function(){
$("#zone-message").append('<div class="alert alert-error fade in" data-alert="alert"><a class="close" data-dismiss="alert" href="#">×</a><p><strong>Woops !</strong> Une erreur est survenue dans la création de la nouvelle campagne. Merci de ré-essayer ultérieurement.</p></div>');
}
},
success : function(campagne){
},
error : function(){
$("#zone-message").append('<div class="alert alert-error fade in" data-alert="alert"><a class="close" data-dismiss="alert" href="#">×</a><p><strong>Woops !</strong> Une erreur est survenue dans la création de la nouvelle société. Merci de ré-essayer ultérieurement.</p></div>');
}
});
}
i'm able to make the .append but the function never get data (passed through campagne, like success ) in my 201 : function(campagne){...}
Any Idea why it's not working like the doc say how it's works ?
Try removing the success and error handlers.

Resources