Discord Interaction failed after 5ish minute - discord.py

I got this problem since i first made the bot, i can't figure it out.. When i use the command ,,MeniuDeTestat2,, The Interaction option works, But after the Loop send the command again, i got ,,This interaction failed" If you can help, please tell me.
import discord
import discord
import asyncio
from discord.ext import commands, tasks
from discord import app_commands
from discord.ui import *
intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix = '!', intents = discord.Intents.all())
bot.remove_command('help')
#bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity = discord.Game(name = "[ Lexa ] Cauta jucatori")) # Discord bot activity
print("Bot has successfully logged in as: {}".format(bot.user))
print("Bot ID: {}\n".format(bot.user.id))
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} command(s)')
except Exception as e:
print(e)
RankRealVal = f"Iron"
GameC = f"0"
#bot.command()
async def MeniuDeTestat2(ctx):
clientid = discord.User.id
#tasks.loop(seconds=300)
async def StartingTheLoop():
await ctx.send("Selecteaza-ti Jocul dorit", view=Games1, delete_after=300)
StartingTheLoop.start()
Games = Select(options=[
discord.SelectOption(label="Valorant", value='1'),
discord.SelectOption(label="Valorant", value='2'),
discord.SelectOption(label="Phasmophobia", value='3'),
discord.SelectOption(label="Phasmophobia", value='4'),])
RanksVal = Select(options=[
discord.SelectOption(label="Iron", value="1"),
discord.SelectOption(label="Bronze", value='2'),
discord.SelectOption(label="Silver",value='3'),
discord.SelectOption(label="Gold", value='4'),
discord.SelectOption(label="Platinum", value='5'),
discord.SelectOption(label="Diamond",value='6'),
discord.SelectOption(label="Ascendant", value='7'),
discord.SelectOption(label="Immortal", value='8'),
discord.SelectOption(label="Radiant",value='9')])
Players = Select(options=[
discord.SelectOption(label="1", value='1'),
discord.SelectOption(label="2", value='2'),
discord.SelectOption(label="3", value='3'),
discord.SelectOption(label="4", value='4'),
discord.SelectOption(label="5", value='5'),
discord.SelectOption(label="5+", value='5+'),
discord.SelectOption(label="10+",value='10+')])
GamemodeVal = Select(options=[
discord.SelectOption(label="Normal", value='1'),
discord.SelectOption(label="Rank", value='2'),
discord.SelectOption(label="Custom",value='3'),
discord.SelectOption(label="MiniGames",value='4')])
Gamemodephasmo = Select(options=[
discord.SelectOption(label="Amateur", value='1'),
discord.SelectOption(label="Intermediate", value='2'),
discord.SelectOption(label="Professional", value='3'),
discord.SelectOption(label="Nightmare", value='4')])
GamemodeAmongus = Select(options=[
discord.SelectOption(label="Normal", value='1'),
discord.SelectOption(label="HideAndSeek", value='2')])
async def games_callback(interaction):
global GameC
if Games.values[0] == "1":
await interaction.response.send_message(f" ``Selecteaza Numarul de Playeri``" , view=Players1,ephemeral=True)
GameC =f"1"
if Games.values[0] == "2":
await interaction.response.send_message(f" ``Selecteaza Numarul de Playeri``" , view=Players1,ephemeral=True)
GameC =f"2"
if Games.values[0] == "3":
await interaction.response.send_message(f" ``Selecteaza Numarul de Playeri``" , view=Players1,ephemeral=True)
GameC =f"3"
async def Players_callback(interaction):
if Games.values[0] == "1":
await interaction.response.send_message(f"`` Selecteaza Rank-ul Necesar al Jucatorilor ``", view=Ranksval2,ephemeral=True)
if Games.values[0] == "2":
await interaction.response.send_message(f"`` Selecteaza Rank-ul Necesar al Jucatorilor ``", view=Ranksval2,ephemeral=True)
if Games.values[0] == "3":
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GMphasmo,ephemeral=True)
if Games.values[0] == "4":
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GMphasmo,ephemeral=True)
async def RanksVal_callback(interaction):
RankVal = 0
if RanksVal.values[0] == "1":
RankVal = RankVal +1
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "2":
RankVal = RankVal +2
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "3":
RankVal = RankVal +3
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "4":
RankVal = RankVal +4
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "5":
RankVal = RankVal +5
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "6":
RankVal = RankVal +6
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "7":
RankVal = RankVal +7
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "8":
RankVal = RankVal +8
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
if RanksVal.values[0] == "9":
RankVal = RankVal +9
await interaction.response.send_message(f"`` Selecteaza-ti Modul Dorit de Joaca ``",view=GamemodeVal1,ephemeral=True)
async def GamemodeVal_callback(interaction):
global RankRealVal
voice_state = interaction.user.voice
if RanksVal.values[0] == "1":
RankRealVal = "<:iron:909401916436521000>"
if RanksVal.values[0] == "2":
RankRealVal = "<:bronze:909401968211026020>"
if RanksVal.values[0] == "3":
RankRealVal = "<:silver:909401980017979422>"
if RanksVal.values[0] == "4":
RankRealVal = "<:gold:909402004508524554>"
if RanksVal.values[0] == "5":
RankRealVal = "<:platinum:909402013647908907>"
if RanksVal.values[0] == "6":
RankRealVal = "<:diamond:909402029909225473>"
if RanksVal.values[0] == "7":
RankRealVal = "<:ascendant:1066771169803522106>"
if RanksVal.values[0] == "8":
RankRealVal = "<:immortal:909402039384158209>"
if RanksVal.values[0] == "9":
RankRealVal = "<:radiant:909402064839376896>"
if GamemodeVal.values[0] == "1":
GamemodeValFinal = f"Normals"
if GamemodeVal.values[0] == "2":
GamemodeValFinal = f"Ranked"
if GamemodeVal.values[0] == "3":
GamemodeValFinal = f"Custom"
if GamemodeVal.values[0] == "4":
GamemodeValFinal = f"Minigames"
if voice_state is None:
await interaction.response.send_message(f"You are not connected to a voice Channel", ephemeral=True)
else:
pfp = interaction.user.avatar.url
ConnectedVC = interaction.user.voice.channel.id
ValEM = discord.Embed(title=f'Looking for {Players.values[0]} Players!',color=0xff5555)
ValEM.set_author(name = f"Name : {interaction.user.name}")
ValEM.add_field(name=f"Rank", value=f"{RankRealVal}",inline=False)
ValEM.add_field(name=f"Gamemode",value=f"{GamemodeValFinal}",inline=False)
ValEM.set_thumbnail(url="https://images.alphacoders.com/128/1282982.jpg")
ValEM.add_field(name=f"VoiceChannel", value=F"<#{ConnectedVC}>")
await interaction.response.send_message(embed=ValEM, delete_after=800)
await ctx.send(f"<#&901585002431647745>", delete_after=800)
async def Gamemodephasmo_callback(interaction):
global RankRealVal
voice_state = interaction.user.voice
if Gamemodephasmo.values[0] == "1":
PhasmoGame = f"Amateur"
if Gamemodephasmo.values[0] == "2":
PhasmoGame = f"Intermediate"
if Gamemodephasmo.values[0] == "3":
PhasmoGame = f"Professional"
if Gamemodephasmo.values[0] == "4":
PhasmoGame = f"NightMare"
if voice_state is None:
await interaction.response.send_message(f"You are not connected to a voice Channel", ephemeral=True)
else:
pfp = interaction.user.avatar.url
ConnectedVC = interaction.user.voice.channel.id
PHASMOEB = discord.Embed(title=f'Looking for {Players.values[0]} Players!',color=0xff5555)
PHASMOEB.set_author(name = f"Name : {interaction.user.name}")
PHASMOEB.add_field(name=f"Gamemode",value=f"{PhasmoGame}",inline=False)
PHASMOEB.set_thumbnail(url="https://cdn.cloudflare.steamstatic.com/steam/apps/739630/header.jpg?t=1674232976")
PHASMOEB.add_field(name=f"VoiceChannel", value=F"<#{ConnectedVC}>")
await interaction.response.send_message(embed=PHASMOEB, delete_after=800)
await ctx.send(f"<#&901585144870240297>" , delete_after=800)
Players.callback = Players_callback
Players1 = View()
Players1.add_item(Players)
RanksVal.callback = RanksVal_callback
Ranksval2 = View()
Ranksval2.add_item(RanksVal)
GamemodeVal.callback = GamemodeVal_callback
GamemodeVal1 = View()
GamemodeVal1.add_item(GamemodeVal)
Gamemodephasmo.callback = Gamemodephasmo_callback
GMphasmo = View()
GMphasmo.add_item(Gamemodephasmo)
Games.callback = games_callback
Games1 = View()
Games1.add_item(Games)
#bot.command()
async def Report(ctx, user: discord.Member):
author = ctx.message.author.name
interaction : discord.interactions
MentionChannel = "<#943623215358541904>"
ReportMeniu = Select(options=[
discord.SelectOption(label="Hacker", value='1'),
discord.SelectOption(label="Limbaj Vulgar", value='2'),
discord.SelectOption(label="Rage Quit", value='3'),
discord.SelectOption(label="Nesimtire", value='4'),])
async def ReportMeniu_callback(interaction):
channel = bot.get_channel(1068951470709407925)
if interaction.user.name == author:
if ReportMeniu.values[0] == "1":
ReportMeniuVal = f"Hacker"
if ReportMeniu.values[0] == "2":
ReportMeniuVal = f"Limbaj Vulgar"
if ReportMeniu.values[0] == "3":
ReportMeniuVal = f"Rage Quiter"
if ReportMeniu.values[0] == "4":
ReportMeniuVal = f"Nesimtit/a"
else:
return
RM = discord.Embed(title=f'Report Facut de : {interaction.user.name}',color=0xff5555)
RM.set_author(name = f"**User Reported : {user}**")
RM.add_field(name= f"Motivul Reportului" , value=f"{ReportMeniuVal}",inline=False)
RM.set_thumbnail(url="https://cdn.pixabay.com/photo/2013/07/13/09/51/unauthorised-156169_960_720.png")
await interaction.response.send_message(f"Multumim pentru Report!")
await channel.send(embed=RM)
ReportMeniu.callback = ReportMeniu_callback
ReportMeniua = View()
ReportMeniua.add_item(ReportMeniu)
if ctx.channel.id ==(1068989418687434862):
await ctx.send(view=ReportMeniua)
else:
await ctx.send(f"**Pentru a folosi aceasta comanda, Foloseste Canalul ** {MentionChannel}")
bot.run('token') # Your Token Here.
The command MeniuDeTestat2 Loops every 5 min.
Image : https://imgur.com/a/IdxeypE

Related

discord py button and select, cant work properly

Can anyone help me with this?
For the button, it shows: IndentationError: unexpected indent
#bot.command()
async def button(ctx):
await ctx.send("hello",components = [
[Button(label="hi",style="3",custom_id="button1"), Button(label="bye",style="4",custom_id="button2")]
])
interaction = await bot.wait_for("button_click", check = lambda i:i.custon_id == "button1" )
await interaction.send(content = "BUtton Clicked", ephemeral=True)
For the select, it only shows urmom...
#bot.command()
async def select(ctx):
await ctx.send("Select", components= [
Select(
placeholder = "Select Something",
options = [
SelectOption(label="A",value="A"),
SelectOption(label="B",value="B")
])
])
while True:
try:
select_interaction = await bot.wait_for("select_option")
await select_interaction.send(content = f"{select_interaction.values[0]} selected", emphemral=False)
except:
await ctx.send("urmom")

Discord.py bot audio streaming cuts off

When I use the stream command on my bot, it streams about 1min 30s of audio before cutting off and not playing audio, and it doesn't give error messages at the start or when cutting off. When I use the download and play command instead, it plays the whole song without errors or cutoffs.
Stream command:
async def play(ctx, *, search):
voiceChannel=ctx.message.author.voice.channel
await voiceChannel.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
query_string = urllib.parse.urlencode({
'search_query': search
})
htm_content = urllib.request.urlopen(
'http://www.youtube.com/results?' + query_string
)
search_results = re.findall(r"watch\?v=(\S{11})", htm_content.read().decode())
url = 'http://www.youtube.com/watch?v=' + search_results[0]
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
song_info = ydl.extract_info(url, download=False)
voice.play(discord.FFmpegPCMAudio(song_info["formats"][0]["url"]))
Download command:
async def download(ctx, *, search):
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except PermissionError:
await ctx.send("Wait for the current playing music to end or use the 'stop' command")
return
voiceChannel=ctx.message.author.voice.channel
await voiceChannel.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
query_string = urllib.parse.urlencode({
'search_query': search
})
htm_content = urllib.request.urlopen(
'http://www.youtube.com/results?' + query_string
)
search_results = re.findall(r"watch\?v=(\S{11})", htm_content.read().decode())
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['http://www.youtube.com/watch?v=' + search_results[0]])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"))
Alright, so I found the answer here on stackoverflow dot com at When playing audio, the last part is cut off. How can this be fixed? (discord.py). I quote, "This is a known issue when you try to make a bot which doesn't download the song it's playing. It is explained here : https://support.discord.com/hc/en-us/articles/360035010351--Known-Issue-Music-Bots-Not-Playing-Music-From-Certain-Sources"
Turns out you just needed to give FFMPEG options to reconnect and play the song as shown in the code below
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
#client.command(
name='play',
description='Streams audio from Youtube. Syntax: w!play [keyword(s)].')
async def play(ctx, *, search):
voiceChannel=ctx.message.author.voice.channel
await voiceChannel.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
query_string = urllib.parse.urlencode({
'search_query': search
})
htm_content = urllib.request.urlopen(
'http://www.youtube.com/results?' + query_string
)
search_results = re.findall(r"watch\?v=(\S{11})", htm_content.read().decode())
url = 'http://www.youtube.com/watch?v=' + search_results[0]
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
song_info = ydl.extract_info(url, download=False)
voice.play(discord.FFmpegPCMAudio(song_info["formats"][0]["url"], **FFMPEG_OPTIONS))
For whatever reason, some

discord.py: custom reason without duty necessarily write them and error message if you don't specify the user

I've been programming with discord.py for 3 days and I'm a beginner, let's say ...
While trying to complete with all possible errors the mute command I noticed that I have to write a reason to execute the command (which I would like to be optional) and that when I don't specify the user the message "specify the user".
How can I solve it?
Here is the complete code
#mute
#client.command()
#commands.has_permissions(ban_members=True)
async def mute(ctx, member: discord.Member=None,*,arg):
role = get(member.guild.roles, id=int("691009285634654229"))
if not member:
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name="Per favore specifica l'utente!",
icon_url="'https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'"
)
await ctx.send(embed=embed)
return
if (ctx.author == member):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name=f'Non puoi mutare te stesso!',
icon_url='https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'
)
await ctx.send(embed=embed)
return
if get(member.roles, name='Mutato'):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name=f'{member.display_name} è attualmente mutato',
icon_url=f'{member.avatar_url}'
)
await ctx.send(embed=embed)
return
if get(member.roles, name='Moderatori'):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name=f'Non puoi mutare un moderatore!',
icon_url='https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'
)
await ctx.send(embed=embed)
return
if get(member.roles, name='Presidente ad Interim del LMII'):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name=f'Non puoi mutare un moderatore!',
icon_url='https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'
)
await ctx.send(embed=embed)
return
if get(member.roles, name='Co-Triumvirato'):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name=f'Non puoi mutare un moderatore!',
icon_url='https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'
)
await ctx.send(embed=embed)
return
if get(member.roles, name='Triumvirato'):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name=f'Non puoi mutare un moderatore!',
icon_url='https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'
)
await ctx.send(embed=embed)
return
embed = discord.Embed(
color=discord.Colour.green()
)
embed.set_author(
name=f'{member.display_name} è stato mutato',
icon_url=f'{member.avatar_url}'
)
embed.set_footer(text=f'Motivo: {arg}')
await member.add_roles(role)
await ctx.send(embed=embed)
embed = discord.Embed(
color=discord.Colour.gold()
)
embed.set_author(
name=f'{ctx.author._user} ha mutato {member._user}',
icon_url=f'{member.avatar_url}'
)
embed.set_footer(text=f'Motivo: {arg}')
embed.add_field(
name='Utente mutato:',
value=f'{member._user}',
inline=True
)
embed.add_field(
name='Mutato da:',
value=f'{ctx.author._user}',
inline=True
)
embed.add_field(
name='Durata:',
value='∞',
inline=True
)
channel = client.get_channel(729553772547932190)
await channel.send(embed=embed)
#mute.error
async def mute_error(ctx, error):
if isinstance(error, commands.CheckFailure):
embed = discord.Embed(
color=discord.Colour.red()
)
embed.set_author(
name="Non ti è permesso mutare",
icon_url='https://cdn.discordapp.com/attachments/640563710104043530/730639329453670420/DuscePeppe_FRIULI.png'
)
await ctx.send(embed=embed)
In regards to the error message, if someone doesn't specify an argument (user) or a wrong/incorrect argument, you can use the following code.
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.BadArgument):
embed=discord.Embed(title="Error", description="You haven't specified the correct arguments.", color=0xff0000)
await ctx.send(embed=embed)
elif isinstance(error, commands.UserNotFound):
embed=discord.Embed(title="Error", description="I could not find the user.", color=0xff0000)
await ctx.send(embed=embed)
elif isinstance(error, commands.MissingRequiredArgument):
embed=discord.Embed(title="Error", description="There are some arguments missing!", color=0xff0000)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Error", description="An unknown error has occured, it has been logged on the bot console", color=0xff0000)
await ctx.send(embed=embed)
raise error

Discord.py Music Bot problem with FFmpeg on heroku

I'm coding my first music bot for discord and successfully tested it on the localhost. After that, I moved it on Heroku and installed FFmpeg buildpack for it. But for some reason, it doesn't work.
Here is proof that I installed FFmpeg buildpack on Heroku: Screen
Here is my code (that works well on localhost):
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
#classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
#client.command()
async def join(ctx):
channel = ctx.message.author.voice.channel
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(channel)
await channel.connect()
#client.command()
async def play(ctx, *, URL):
async with ctx.typing():
player = await YTDLSource.from_url(url)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(player.title))

Why does `chrome.notifications.update` only update once on Windows 10?

I'm developing a chrome extension that initiates a 3 seconds countdown using notifications. It works by creating an initial notification "recording in 3 seconds" and then updating that notification every second:
background-script.js
const waitForMs = (ms) => new Promise(r => setTimeout(r, ms))
const displayNotification = (message, updateNotificationId = undefined, expireInMs = undefined) => new Promise(
(resolve) => {
const notificationOptions = {
type: 'basic',
iconUrl: 'icon.png', // required
title: message,
message,
// Avoids sounds and vibrations
silent: true,
// Required to have notification update in real-time
requireInteraction: true
}
// Resolves with given notification id, possibly after clearing after timeout
const resolveWithId = async (id) => {
if (typeof expireInMs === 'number') {
await waitForMs(expireInMs)
chrome.notifications.clear(id)
}
resolve(id)
}
// Update if notification id is defined
// Otherwise create a new notification
if (typeof updateNotificationId === 'string') {
chrome.notifications.update(
updateNotificationId,
notificationOptions,
(updated) => {
console.log(`updated? ${updated}`)
resolveWithId(updateNotificationId)
}
)
}
else {
chrome.notifications.create(
notificationOptions,
(id) => resolveWithId(id)
)
}
}
)
chrome.browserAction.onClicked.addListener(() => {
chrome.notifications.getPermissionLevel(async (permissionLevel) => {
console.log(`permissionLevel: ${permissionLevel}`)
if (permissionLevel === 'granted') {
const notificationId = await displayNotification('Recording in 3...')
await waitForMs(1000)
await displayNotification('Recording in 2...', notificationId)
await waitForMs(1000)
await displayNotification('Recording in 1...', notificationId)
await waitForMs(1000)
await displayNotification('Now recording!', notificationId, 3000)
}
})
})
manifest.json:
{
"name": "NotificationExample",
"short_name": "NotificationExample",
"version": "1.0.0",
"manifest_version": 2,
"description": "",
"background": {
"scripts": [
"background-script.js"
],
"persistent": false
},
"browser_action": {
"default_title": "Notification Countdown Example"
},
"permissions": [
"notifications"
]
}
However, as you can see in this screen recording, on Windows 10 the notification is only updated successfully once (from 3 seconds to 2 seconds), and does not update the 3rd or 4th time. On MacOS it does work. Why does this not work on Windows 10 and how could this be resolved?

Resources