discordpy 2.0 interaction is a required argument that is missing - discord.py

#client.command(brief="Send a message with a button!")
async def button(ctx,interaction: discord.Interaction):
view = discord.ui.View()
style = discord.ButtonStyle.gray
item = discord.ui.Button(style=style, label="Read the docs!", url="https://discordpy.readthedocs.io/en/master")
view.add_item(item=item)
await interaction.response.send_message("This message has buttons!", view=view)
await interaction.response.send_message(content="Hi", ephemeral=True)
discord.ext.commands.errors.MissingRequiredArgument: interaction is a required argument that is missing.
Actually i just want to send a message by intraction, but seem itwasn't work :(

I think you are confused about the basic concepts since your code is mixed up command and interaction stuffs.
If you want to create button, you cannot write in the older command way like #client.command. You need to either use application command or hybrid command (which is a mix of interaction and command)
So, you should never have something like (ctx: Context, interaction: Interaction) together.
Also, classically, you need to create a view class and create a button inside this view class. Then you can attach this view to your message or embed when you send this to the user.
And, if you want to respond to user multiple times in a application command, you cannot do that through interaction.response (only once). You can use interaction.followup() for later responses. link
For view examples, see file example under this
For slash command (application command) example, see this

Related

How and in what way do content scripts share content scoped variables across different web pages?

There are some key parts of the MDN content script documentation I am having trouble understanding regarding variable scope:
There is only one global scope per frame, per extension. This means that variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.
This paragraph may also be relevant (my italics) given the questions below:
... you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
I assume (testing all this has proved difficult, please bear with me) that this means:
The content script code will be run every time a new page is loaded that matches the URLs provided in manifest.json (in my case "matches": [<"all_urls">]
The content script code will run every time a page is refreshed/reloaded.
The content script code will not be run when a user switches between already open tabs (requires listening to window focus or tabs.onActivated events).
The variables initialized on one page via the content script share a global scope with those variables initialized by the same content script on another page.
Given the following code,
background-script.js:
let contentPort = null
async function connectToActiveTab () {
let tab = await browser.tabs.query({ active: true, currentWindow: true })
tab = tab[0]
const tabName = `tab-${tab.id}`
if (contentPort) {
contentPort.disconnect()
}
contentPort = await browser.tabs.connect(tab.id, { name: tabName })
}
// listening to onCreated probably not needed so long as content script reliably sends 'connecToActiveTab' message
browser.tabs.onCreated.addListener(connectToActiveTab)
browser.runtime.onMessage.addListener(connectToActiveTab)
content-script.js
let contentPort = null
function connectionHandler (port, info) {
if (contentPort && contentPort.name !== port.name) {
// if content port doesn't match port we have changed tabs/windows
contentPort.disconnect()
}
if (!contentPort) {
contentPort = port
contentPort.onMessage.addListener(messageHandler)
}
}
async function main () {
// should always be true when a new page opens since content script code is run on each new page, testing has shown inconsistent results
if (!contentPort) {
await browser.runtime.sendMessage({ type: 'connectToActiveTab' })
}
}
browser.runtime.onConnect.addListener(connectionHandler)
main()
And from assumptions 1 and 4, I also assume:
The existing contentPort (if defined) will fire a disconnect event (which I could handle in the background script) and be replaced by a new connection to the currently active tab each time a new tab is opened.
The behaviour I have seen in Firefox while testing has so far been a bit erratic and I think I may be doing some things wrong. So now, here are the specific questions:
Are all of my 5 assumptions true? If not, which ones are not?
Is firing the disconnect() event unnecessary, since I should rely on Firefox to properly clean up and close existing connections without manually firing a disconnect event once the original contentPort variable is overwritten? (the code here would suggest otherwise)
Are the connect() methods synchronous, thus negating the need for await and asynchronous functions given the example code?
The tabs.connect() examples don't use await but neither the MDN runtime or connect docs explicitly say whether the methods are synchronous or not.
Thanks for taking the time to go through these deep dive questions regarding content script behaviour, my hope is that clear and concise answers to these could perhaps be added to the SO extension FAQ pages/knowledge base.

Is there a way to make this 'undefined' object safe?

On a page in a web app, a loading screen/widget continue to appear after the user leaves the text field.
The app is using version 1.6.0.3. I looked at the most recent version of Prototype 1.7.3 and I did not find that function.
I also tested other instances when this method is called. If there is no user input, the widget does not hang-up.
This error is displayed in the console of Chrome’s developer tools.
at E (framework.pack.js:1699)
at Function.stopObserving (framework.pack.js:1732)
at A.hide (ui.pack.js:13410)
at A.render (ui.pack.js:13591)
at A.updateChoices (ui.pack.js:13650)
at A.onComplete (ui.pack.js:13786)
at Object.oncomplete (framework.pack.js:76)
at framework.pack.js:2748
The specific method in questions seems to be in the Prototype.js file this =>
if (element._prototypeEventID) return element._prototypeEventID[0];
arguments.callee.id = arguments.callee.id || 1;
return element._prototypeEventID = [++arguments.callee.id];
}
I expect the loading widget to disappear after the save is done, but it is still on the page. The console of Chrome's developer tools also has a second error:
validateFormCheck # common.js:1031
It looks like the getEventID method is being called where the undefined warning/error triggers.
In version 1.6.0.3 getEventID is only called in createWrapper and stopObserving, I see stopObserving is in the call stack that you posted so let's go with that one.
stopObserving() takes 1 required parameter and 2 optional parameters (element, eventName, handler) if you only pass the element to the function it looks it up and then deletes all the PrototypeJS observers attached to that element. If you pass eventName and/or handler as well stopObserving will only specifically delete the observer you tell it to.
That being said, if the element is removed from the DOM before stopObserving is called this could cause the error you are seeing.
2 fixes that could work
move the call to stopObserving() above the call to remove()
comment out the call to stopObserving() and see if page behaves like you want it to

Difference between marionette events

I am reading the marionette.js docs and I don't understand the difference between vent, reqres and commands.
The only thing I clearly understood is that commands should not return anything.
Can anyone explain it a little bit?
Let's start from the top: Backbone.wreqr is a Backbone plugin that ships with Marionette. It provides three messaging patterns for loosely-coupled applications.
This answer includes example code from the Backbone.wreqr documentation - credit to the original authors.
Events
EventAggregator objects work like Backbone.Events - they enable namespaced event handing. vent is simply a common variable name for an EventAggregator object:
var vent = new Backbone.Wreqr.EventAggregator();
vent.on("foo", function(){
console.log("foo event");
});
vent.trigger("foo");
Commands
Commands are very similar to Events. The difference is semantic - an event informs other parts of the application that something has happened. A command instructs another part of the application to do something.
var commands = new Backbone.Wreqr.Commands();
commands.setHandler("foo", function(){
console.log("the foo command was executed");
});
commands.execute("foo");
Request/Response
RequestResponse objects, which are often referenced by a variable called reqres, provide a loosely-coupled way for application components to request access to objects:
var reqres = new Backbone.Wreqr.RequestResponse();
reqres.setHandler("foo", function(){
return "foo requested. this is the response";
});
var result = reqres.request("foo");
console.log(result);
Radio and Channels
As a convenience, Wreqr provides an object called radio which mixes in the three messaging patterns. Commands, events and requests can be grouped into logical channels to prevent interference - you may need distinct save commands for user and document channels, for example.
In Marionette
Marionette.Application creates instances of Commands, RequestResponse and EventAggregator inside a channel ("global" by default) using the conventional variable names. If you need custom behaviour you can override the vent, commands and reqres variables.
_initChannel: function() {
this.channelName = _.result(this, 'channelName') || 'global';
this.channel = _.result(this, 'channel') || Backbone.Wreqr.radio.channel(this.channelName);
this.vent = _.result(this, 'vent') || this.channel.vent;
this.commands = _.result(this, 'commands') || this.channel.commands;
this.reqres = _.result(this, 'reqres') || this.channel.reqres;
},
Link to source
I suggest you read the Wreqr docs for more detail. I also recommend reading through the Marionette annotated source - it is concise and very well documented and, in fact, includes the Wreqr source.
N.B. The next major release of Marionnette, v3.x, replaces Wreqr with Radio. Radio provides the same functionality as Wreqr with a cleaner API. It is possible to use Radio in Marionette 2.x applications, which I recommend if you are starting a new app.
ReqRes Messenger
The reqres messenger can both send a message, (which consists of the named event as well as optional parameters), to a target and relay a response back to the source (which will be in the form of the returned parameter of the target function)
Command Messenger
The command and vent messengers are functionally very similar, but fulfill different semantic responsibilities.
The command messenger is used to invoke the execution of a target function. Generally, one function is bound to a command handler. Like the OP stated, in a command the direction of communication is one-way, meaning that whatever the command target returns will not be sent back to the source incoming the command.
VENT Messenger
Finally, vent messengers are event aggregators. You can attach (subscribe) many listeners to the vent and all of them will receive an event that is triggered (published) by the vent. Each listener will invoke a function associated with that listener When an event in a vent is triggered it may also send each listener a set of parameters.

How to use querycommands in CKEditor

In TinyMCE i am able to get the currently selected values by using queryCommandValue and queryCommandState like this:
tinymce.activeEditor.queryCommandValue("FontName");
This would get me the selected fontname. How would i do something like this in CKEditor?
The command state can be checked using the following available methods in CKEDITOR.command list.
previousState
Indicates the previous command state.
alert( command.previousState );
state
Indicates the editor state. Possible values are:
CKEDITOR.TRISTATE_DISABLED: the command is disabled. It's execution will have no effect. Same as disable.
CKEDITOR.TRISTATE_ON: the command is enabled and currently active in the editor (for context sensitive commands, for example).
CKEDITOR.TRISTATE_OFF: the command is enabled and currently inactive in the editor (for context sensitive commands, for example).
Do not set this property directly, this can also be achieved using the #setState method instead.
e.g
command.setState( CKEDITOR.TRISTATE_ON );
one can also check the state to do execute a command or to do some task
if ( command.state == CKEDITOR.TRISTATE_DISABLED )
alert( 'This command is disabled' );
queryCommandValue can be done while executing a normal command like command.exec(data) and this value of data should come from some variable in which this value is stored.
You can get the document to perform direct DOM calls as you want by doing it this way
CKEDITOR.instances.editor1.document.$.queryCommandValue("FontName")
but I must warn you that directly calling the DOM instead of using the CKEditor API is gonna be harder. CKEditor has been designed to wrap the differences between browsers, and if you want to skip that and use other API then you'll have to redo a lot of work.

Logging an onFailure inError in WebOS

An onFailure handler in webOS has an argument inError. I tried printing it using: console.log("error: " + inError);, but the result is only: error: [object Object]*** (app/assistants/main-assistant.js:26), which isn't much use. How can I log something more useful instead?
Update:
Ares generates: alarm1Failure: function(inSender, inError) {}. However, the error is contained as the errorText property of the first object and the second object is the request
I would use the interactive debugger at:
http://ares.palm.com/AresDebug/
Connect your device and run your app. Put your app name in the 'Script Filter' box and click get scripts.
Now use the 'Available Scripts' pull down to find your assembly.
You can set breakpoints (click on line numbers to the left) and inspect variables using the lower left pane and '>' prompt.
Be sure to use Chrome or Safari as it will not work with IE.
There is also a logger at:
http://ares.palm.com/AresLog/
if you don't want to use the debugger, then you probably should know something about the inError object getting returned to you. In this case I assume the onFailure comes from a Protocol function's callback, so try looking in the Protocol documentation to see what information the error object should contain.
Also for any logging purposes don't forget about the imensely useful function
JSON.stringify(obj)
It will take an object and return a JSON representation that you can log so you can see all the properties at once.

Resources