aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorXua <[email protected]>2020-01-23 19:25:04 +1300
committerRapptz <[email protected]>2020-01-24 19:32:24 -0500
commit1fd87ad0cab5d45602192c83681340d5da27a6db (patch)
treed90c45997d39b4fad4f0cdf6a2768258cee3ec07 /examples
parentMention that you can create Permissions via kwargs now (diff)
downloaddiscord.py-1fd87ad0cab5d45602192c83681340d5da27a6db.tar.xz
discord.py-1fd87ad0cab5d45602192c83681340d5da27a6db.zip
Add example on subclassing commands.Context
Diffstat (limited to 'examples')
-rw-r--r--examples/custom_context.py51
1 files changed, 51 insertions, 0 deletions
diff --git a/examples/custom_context.py b/examples/custom_context.py
new file mode 100644
index 00000000..bc2a174d
--- /dev/null
+++ b/examples/custom_context.py
@@ -0,0 +1,51 @@
+import random
+
+import discord
+from discord.ext import commands
+
+
+class MyContext(commands.Context):
+ async def tick(self, value):
+ # reacts to the message with an emoji
+ # depending on whether value is True or False
+ # if its True, it'll add a green check mark
+ # otherwise, it'll add a red cross mark
+ emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
+ try:
+ # this will react to the command author's message
+ await self.message.add_reaction(emoji)
+ except discord.HTTPException:
+ # sometimes errors occur during this, for example
+ # maybe you dont have permission to do that
+ # we dont mind, so we can just ignore them
+ pass
+
+
+class MyBot(commands.Bot):
+ async def get_context(self, message, *, cls=MyContext):
+ # when you override this method, you pass your new Context
+ # subclass to the super() method, which tells the bot to
+ # use the new MyContext class
+ return await super().get_context(message, cls=cls)
+
+
+bot = MyBot(command_prefix='!')
+
+async def guess(ctx, number: int):
+ """ Guess a random number from 1 to 6. """
+ # explained in a previous example, this gives you
+ # a random number from 1-6
+ value = random.randint(1, 6)
+ # with your new helper function, you can add a
+ # green check mark if the guess was correct,
+ # or a red cross mark if it wasnt
+ await ctx.tick(number == value)
+
+# important: you shouldnt hard code your token
+# these are very important, and leaking them can
+# let people do very malicious things with your
+# bot. try to use a file or something to keep
+# them private, and dont commit it to GitHub
+token = "your token here"
+bot.run(token)