id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
160,864 | import heapq
import math
import random
import time
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
AI_DEFAULT,
AI_HANDICAP,
AI_INFLUENCE,
AI_INFLUENCE_ELO_GRID,
AI_JIGO,
AI_ANTIMIRROR,
AI_LOCAL,
AI_LOCAL_ELO_GRID,
AI_PICK,
AI_PICK_ELO_GRID,
AI_POLICY,
AI_RANK,
AI_SCORELOSS,
AI_SCORELOSS_ELO,
AI_SETTLE_STONES,
AI_SIMPLE_OWNERSHIP,
AI_STRATEGIES_PICK,
AI_STRATEGIES_POLICY,
AI_STRENGTH,
AI_TENUKI,
AI_TENUKI_ELO_GRID,
AI_TERRITORY,
AI_TERRITORY_ELO_GRID,
AI_WEIGHTED,
AI_WEIGHTED_ELO,
CALIBRATED_RANK_ELO,
OUTPUT_DEBUG,
OUTPUT_ERROR,
OUTPUT_INFO,
PRIORITY_EXTRA_AI_QUERY,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.game import Game, GameNode, Move
from katrain.core.utils import var_to_grid, weighted_selection_without_replacement, evaluation_class
def fmt_moves(moves: List[Tuple[float, Move]]):
return ", ".join(f"{mv.gtp()} ({p:.2%})" for p, mv in moves)
def policy_weighted_move(policy_moves, lower_bound, weaken_fac):
lower_bound, weaken_fac = max(0, lower_bound), max(0.01, weaken_fac)
weighted_coords = [
(pv, pv ** (1 / weaken_fac), move) for pv, move in policy_moves if pv > lower_bound and not move.is_pass
]
if weighted_coords:
top = weighted_selection_without_replacement(weighted_coords, 1)[0]
move = top[2]
ai_thoughts = f"Playing policy-weighted random move {move.gtp()} ({top[0]:.1%}) from {len(weighted_coords)} moves above lower_bound of {lower_bound:.1%}."
else:
move = policy_moves[0][1]
ai_thoughts = f"Playing top policy move because no non-pass move > above lower_bound of {lower_bound:.1%}."
return move, ai_thoughts
def generate_influence_territory_weights(ai_mode, ai_settings, policy_grid, size):
thr_line = ai_settings["threshold"] - 1 # zero-based
if ai_mode == AI_INFLUENCE:
weight = lambda x, y: (1 / ai_settings["line_weight"]) ** ( # noqa E731
max(0, thr_line - min(size[0] - 1 - x, x)) + max(0, thr_line - min(size[1] - 1 - y, y))
) # noqa E731
else:
weight = lambda x, y: (1 / ai_settings["line_weight"]) ** ( # noqa E731
max(0, min(size[0] - 1 - x, x, size[1] - 1 - y, y) - thr_line)
)
weighted_coords = [
(policy_grid[y][x] * weight(x, y), weight(x, y), x, y)
for x in range(size[0])
for y in range(size[1])
if policy_grid[y][x] > 0
]
ai_thoughts = f"Generated weights for {ai_mode} according to weight factor {ai_settings['line_weight']} and distance from {thr_line + 1}th line. "
return weighted_coords, ai_thoughts
def generate_local_tenuki_weights(ai_mode, ai_settings, policy_grid, cn, size):
var = ai_settings["stddev"] ** 2
mx, my = cn.move.coords
weighted_coords = [
(policy_grid[y][x], math.exp(-0.5 * ((x - mx) ** 2 + (y - my) ** 2) / var), x, y)
for x in range(size[0])
for y in range(size[1])
if policy_grid[y][x] > 0
]
ai_thoughts = f"Generated weights based on one minus gaussian with variance {var} around coordinates {mx},{my}. "
if ai_mode == AI_TENUKI:
weighted_coords = [(p, 1 - w, x, y) for p, w, x, y in weighted_coords]
ai_thoughts = (
f"Generated weights based on one minus gaussian with variance {var} around coordinates {mx},{my}. "
)
return weighted_coords, ai_thoughts
def request_ai_analysis(game: Game, cn: GameNode, extra_settings: Dict) -> Optional[Dict]:
error = False
analysis = None
def set_analysis(a, partial_result):
nonlocal analysis
if not partial_result:
analysis = a
def set_error(a):
nonlocal error
game.katrain.log(f"Error in additional analysis query: {a}")
error = True
engine = game.engines[cn.player]
engine.request_analysis(
cn,
callback=set_analysis,
error_callback=set_error,
priority=PRIORITY_EXTRA_AI_QUERY,
ownership=False,
extra_settings=extra_settings,
)
while not (error or analysis):
time.sleep(0.01) # TODO: prevent deadlock if esc, check node in queries?
engine.check_alive(exception_if_dead=True)
return analysis
OUTPUT_ERROR = -1
OUTPUT_INFO = 0
OUTPUT_DEBUG = 1
AI_DEFAULT = "ai:default"
AI_HANDICAP = "ai:handicap"
AI_SCORELOSS = "ai:scoreloss"
AI_WEIGHTED = "ai:p:weighted"
AI_JIGO = "ai:jigo"
AI_ANTIMIRROR = "ai:antimirror"
AI_POLICY = "ai:policy"
AI_LOCAL = "ai:p:local"
AI_TENUKI = "ai:p:tenuki"
AI_INFLUENCE = "ai:p:influence"
AI_TERRITORY = "ai:p:territory"
AI_RANK = "ai:p:rank"
AI_SIMPLE_OWNERSHIP = "ai:simple"
AI_SETTLE_STONES = "ai:settle"
AI_STRATEGIES_PICK = [AI_PICK, AI_LOCAL, AI_TENUKI, AI_INFLUENCE, AI_TERRITORY, AI_RANK]
AI_STRATEGIES_POLICY = [AI_WEIGHTED, AI_POLICY] + AI_STRATEGIES_PICK
class Game(BaseGame):
"""Extensions related to analysis etc."""
def __init__(
self,
katrain,
engine: Union[Dict, KataGoEngine],
move_tree: GameNode = None,
analyze_fast=False,
game_properties: Optional[Dict] = None,
sgf_filename=None,
):
super().__init__(
katrain=katrain, move_tree=move_tree, game_properties=game_properties, sgf_filename=sgf_filename
)
if not isinstance(engine, Dict):
engine = {"B": engine, "W": engine}
self.engines = engine
self.insert_mode = False
self.insert_after = None
self.region_of_interest = None
threading.Thread(
target=lambda: self.analyze_all_nodes(analyze_fast=analyze_fast, even_if_present=False),
daemon=True,
).start() # return faster, but bypass Kivy Clock
def analyze_all_nodes(self, priority=PRIORITY_GAME_ANALYSIS, analyze_fast=False, even_if_present=True):
for node in self.root.nodes_in_tree:
# forced, or not present, or something went wrong in loading
if even_if_present or not node.analysis_from_sgf or not node.load_analysis():
node.clear_analysis()
node.analyze(self.engines[node.next_player], priority=priority, analyze_fast=analyze_fast)
def set_current_node(self, node):
if self.insert_mode:
self.katrain.controls.set_status(i18n._("finish inserting before navigating"), STATUS_ERROR)
return
super().set_current_node(node)
def undo(self, n_times=1, stop_on_mistake=None):
if self.insert_mode: # in insert mode, undo = delete
cn = self.current_node # avoid race conditions
if n_times == 1 and cn not in self.insert_after.nodes_from_root:
cn.parent.children = [c for c in cn.parent.children if c != cn]
self.current_node = cn.parent
self._calculate_groups()
return
super().undo(n_times=n_times, stop_on_mistake=stop_on_mistake)
def reset_current_analysis(self):
cn = self.current_node
engine = self.engines[cn.next_player]
engine.terminate_queries(cn)
cn.clear_analysis()
cn.analyze(engine)
def redo(self, n_times=1, stop_on_mistake=None):
if self.insert_mode:
return
super().redo(n_times=n_times, stop_on_mistake=stop_on_mistake)
def set_insert_mode(self, mode):
if mode == "toggle":
mode = not self.insert_mode
if mode == self.insert_mode:
return
self.insert_mode = mode
if mode:
children = self.current_node.ordered_children
if not children:
self.insert_mode = False
else:
self.insert_after = self.current_node.ordered_children[0]
self.katrain.controls.set_status(i18n._("starting insert mode"), STATUS_INFO)
else:
copy_from_node = self.insert_after
copy_to_node = self.current_node
num_copied = 0
if copy_to_node != self.insert_after.parent:
above_insertion_root = self.insert_after.parent.nodes_from_root
already_inserted_moves = [
n.move for n in copy_to_node.nodes_from_root if n not in above_insertion_root and n.move
]
try:
while True:
for m in copy_from_node.move_with_placements:
if m not in already_inserted_moves:
self._validate_move_and_update_chains(m, True)
# this inserts
copy_to_node = GameNode(
parent=copy_to_node, properties=copy.deepcopy(copy_from_node.properties)
)
num_copied += 1
if not copy_from_node.children:
break
copy_from_node = copy_from_node.ordered_children[0]
except IllegalMoveException:
pass # illegal move = stop
self._calculate_groups() # recalculate groups
self.katrain.controls.set_status(
i18n._("ending insert mode").format(num_copied=num_copied), STATUS_INFO
)
self.analyze_all_nodes(analyze_fast=True, even_if_present=False)
else:
self.katrain.controls.set_status("", STATUS_INFO)
self.katrain.controls.move_tree.insert_node = self.insert_after if self.insert_mode else None
self.katrain.controls.move_tree.redraw()
self.katrain.update_state(redraw_board=True)
# Play a Move from the current position, raise IllegalMoveException if invalid.
def play(self, move: Move, ignore_ko: bool = False, analyze=True):
played_node = super().play(move, ignore_ko)
if analyze:
if self.region_of_interest:
played_node.analyze(self.engines[played_node.next_player], analyze_fast=True)
played_node.analyze(self.engines[played_node.next_player], region_of_interest=self.region_of_interest)
else:
played_node.analyze(self.engines[played_node.next_player])
return played_node
def set_region_of_interest(self, region_of_interest):
x1, x2, y1, y2 = region_of_interest
xmin, xmax = min(x1, x2), max(x1, x2)
ymin, ymax = min(y1, y2), max(y1, y2)
szx, szy = self.board_size
if not (xmin == xmax and ymin == ymax) and not (xmax - xmin + 1 >= szx and ymax - ymin + 1 >= szy):
self.region_of_interest = [xmin, xmax, ymin, ymax]
else:
self.region_of_interest = None
self.katrain.controls.set_status("", OUTPUT_INFO)
def analyze_extra(self, mode, **kwargs):
stones = {s.coords for s in self.stones}
cn = self.current_node
if mode == "stop":
self.katrain.pondering = False
for e in set(self.engines.values()):
e.stop_pondering()
e.terminate_queries()
return
engine = self.engines[cn.next_player]
if mode == "ponder":
cn.analyze(
engine,
ponder=True,
priority=PRIORITY_EXTRA_ANALYSIS,
region_of_interest=self.region_of_interest,
time_limit=False,
)
return
if mode == "extra":
visits = cn.analysis_visits_requested + engine.config["max_visits"]
self.katrain.controls.set_status(i18n._("extra analysis").format(visits=visits), STATUS_ANALYSIS)
cn.analyze(
engine,
visits=visits,
priority=PRIORITY_EXTRA_ANALYSIS,
region_of_interest=self.region_of_interest,
time_limit=False,
)
return
if mode == "game":
nodes = self.root.nodes_in_tree
only_mistakes = kwargs.get("mistakes_only", False)
move_range = kwargs.get("move_range", None)
if move_range:
if move_range[1] < move_range[0]:
move_range = reversed(move_range)
threshold = self.katrain.config("trainer/eval_thresholds")[-4]
if "visits" in kwargs:
visits = kwargs["visits"]
else:
min_visits = min(node.analysis_visits_requested for node in nodes)
visits = min_visits + engine.config["max_visits"]
for node in nodes:
max_point_loss = max(c.points_lost or 0 for c in [node] + node.children)
if only_mistakes and max_point_loss <= threshold:
continue
if move_range and (not node.depth - 1 in range(move_range[0], move_range[1] + 1)):
continue
node.analyze(engine, visits=visits, priority=-1_000_000, time_limit=False, report_every=None)
if not move_range:
self.katrain.controls.set_status(i18n._("game re-analysis").format(visits=visits), STATUS_ANALYSIS)
else:
self.katrain.controls.set_status(
i18n._("move range analysis").format(
start_move=move_range[0], end_move=move_range[1], visits=visits
),
STATUS_ANALYSIS,
)
return
elif mode == "sweep":
board_size_x, board_size_y = self.board_size
if cn.analysis_exists:
policy_grid = (
var_to_grid(self.current_node.policy, size=(board_size_x, board_size_y))
if self.current_node.policy
else None
)
analyze_moves = sorted(
[
Move(coords=(x, y), player=cn.next_player)
for x in range(board_size_x)
for y in range(board_size_y)
if (policy_grid is None and (x, y) not in stones) or policy_grid[y][x] >= 0
],
key=lambda mv: -policy_grid[mv.coords[1]][mv.coords[0]],
)
else:
analyze_moves = [
Move(coords=(x, y), player=cn.next_player)
for x in range(board_size_x)
for y in range(board_size_y)
if (x, y) not in stones
]
visits = engine.config["fast_visits"]
self.katrain.controls.set_status(i18n._("sweep analysis").format(visits=visits), STATUS_ANALYSIS)
priority = PRIORITY_SWEEP
elif mode in ["equalize", "alternative", "local"]:
if not cn.analysis_complete and mode != "local":
self.katrain.controls.set_status(i18n._("wait-before-extra-analysis"), STATUS_INFO, self.current_node)
return
if mode == "alternative": # also do a quick update on current candidates so it doesn't look too weird
self.katrain.controls.set_status(i18n._("alternative analysis"), STATUS_ANALYSIS)
cn.analyze(engine, priority=PRIORITY_ALTERNATIVES, time_limit=False, find_alternatives="alternative")
visits = engine.config["fast_visits"]
else: # equalize
visits = max(d["visits"] for d in cn.analysis["moves"].values())
self.katrain.controls.set_status(i18n._("equalizing analysis").format(visits=visits), STATUS_ANALYSIS)
priority = PRIORITY_EQUALIZE
analyze_moves = [Move.from_gtp(gtp, player=cn.next_player) for gtp, _ in cn.analysis["moves"].items()]
else:
raise ValueError("Invalid analysis mode")
for move in analyze_moves:
if cn.analysis["moves"].get(move.gtp(), {"visits": 0})["visits"] < visits:
cn.analyze(
engine, priority=priority, visits=visits, refine_move=move, time_limit=False
) # explicitly requested so take as long as you need
def selfplay(self, until_move, target_b_advantage=None):
cn = self.current_node
if target_b_advantage is not None:
analysis_kwargs = {"visits": max(25, self.katrain.config("engine/fast_visits"))}
engine_settings = {"wideRootNoise": 0.03}
else:
analysis_kwargs = engine_settings = {}
def set_analysis(node, result):
node.set_analysis(result)
analyze_and_play(node)
def request_analysis_for_node(node):
self.engines[node.player].request_analysis(
node,
callback=lambda result, _partial: set_analysis(node, result),
priority=PRIORITY_DEFAULT,
analyze_fast=True,
extra_settings=engine_settings,
**analysis_kwargs,
)
def analyze_and_play(node):
nonlocal cn, engine_settings
candidates = node.candidate_moves
if self.katrain.game is not self:
return # a new game happened
ai_thoughts = "Move generated by AI self-play\n"
if until_move != "end" and target_b_advantage is not None: # setup pos
if node.depth >= until_move or candidates[0]["move"] == "pass":
self.set_current_node(node)
return
target_score = cn.score + (node.depth - cn.depth + 1) * (target_b_advantage - cn.score) / (
until_move - cn.depth
)
max_loss = 5
stddev = min(3, 0.5 + (until_move - node.depth) * 0.15)
ai_thoughts += f"Selecting moves aiming at score {target_score:.1f} +/- {stddev:.2f} with < {max_loss} points lost\n"
if abs(node.score - target_score) < 3 * stddev:
weighted_cands = [
(
move,
math.exp(-0.5 * (abs(move["scoreLead"] - target_score) / stddev) ** 2)
* math.exp(-0.5 * (min(0, move["pointsLost"]) / max_loss) ** 2),
)
for i, move in enumerate(candidates)
if move["pointsLost"] < max_loss or i == 0
]
move_info = weighted_selection_without_replacement(weighted_cands, 1)[0][0]
for move, wt in weighted_cands:
self.katrain.log(
f"{'* ' if move_info == move else ' '} {move['move']} {move['scoreLead']} {wt}",
OUTPUT_EXTRA_DEBUG,
)
ai_thoughts += f"Move option: {move['move']} score {move['scoreLead']:.2f} loss {move['pointsLost']:.2f} weight {wt:.3e}\n"
else: # we're a bit lost, far away from target, just push it closer
move_info = min(candidates, key=lambda move: abs(move["scoreLead"] - target_score))
self.katrain.log(
f"* Played {move_info['move']} {move_info['scoreLead']} because score deviation between current score {node.score} and target score {target_score} > {3*stddev}",
OUTPUT_EXTRA_DEBUG,
)
ai_thoughts += f"Move played to close difference between score {node.score:.1f} and target {target_score:.1f} quickly."
self.katrain.log(
f"Self-play until {until_move} target {target_b_advantage}: {len(candidates)} candidates -> move {move_info['move']} score {move_info['scoreLead']} point loss {move_info['pointsLost']}",
OUTPUT_DEBUG,
)
move = Move.from_gtp(move_info["move"], player=node.next_player)
elif candidates: # just selfplay to end
move = Move.from_gtp(candidates[0]["move"], player=node.next_player)
else: # 1 visit etc
polmoves = node.policy_ranking
move = polmoves[0][1] if polmoves else Move(None)
if move.is_pass:
if self.current_node == cn:
self.set_current_node(node)
return
new_node = GameNode(parent=node, move=move)
new_node.ai_thoughts = ai_thoughts
if until_move != "end" and target_b_advantage is not None:
self.set_current_node(new_node)
self.katrain.controls.set_status(
i18n._("setup game status message").format(move=new_node.depth, until_move=until_move),
STATUS_INFO,
)
else:
if node != cn:
node.remove_shortcut()
cn.add_shortcut(new_node)
self.katrain.controls.move_tree.redraw_tree_trigger()
request_analysis_for_node(new_node)
request_analysis_for_node(cn)
def analyze_undo(self, node):
train_config = self.katrain.config("trainer")
move = node.move
if node != self.current_node or node.auto_undo is not None or not node.analysis_complete or not move:
return
points_lost = node.points_lost
thresholds = train_config["eval_thresholds"]
num_undo_prompts = train_config["num_undo_prompts"]
i = 0
while i < len(thresholds) and points_lost < thresholds[i]:
i += 1
num_undos = num_undo_prompts[i] if i < len(num_undo_prompts) else 0
if num_undos == 0:
undo = False
elif num_undos < 1: # probability
undo = int(node.undo_threshold < num_undos) and len(node.parent.children) == 1
else:
undo = len(node.parent.children) <= num_undos
node.auto_undo = undo
if undo:
self.undo(1)
self.katrain.controls.set_status(
i18n._("teaching undo message").format(move=move.gtp(), points_lost=points_lost), STATUS_TEACHING
)
self.katrain.update_state()
def var_to_grid(array_var: List[T], size: Tuple[int, int]) -> List[List[T]]:
"""convert ownership/policy to grid format such that grid[y][x] is for move with coords x,y"""
ix = 0
grid = [[]] * size[1]
for y in range(size[1] - 1, -1, -1):
grid[y] = array_var[ix : ix + size[0]]
ix += size[0]
return grid
def weighted_selection_without_replacement(items: List[Tuple], pick_n: int) -> List[Tuple]:
"""For a list of tuples where the second element is a weight, returns random items with those weights, without replacement."""
elt = [(math.log(random.random()) / (item[1] + 1e-18), item) for item in items] # magic
return [e[1] for e in heapq.nlargest(pick_n, elt)] # NB fine if too small
def generate_ai_move(game: Game, ai_mode: str, ai_settings: Dict) -> Tuple[Move, GameNode]:
cn = game.current_node
if ai_mode == AI_HANDICAP:
pda = ai_settings["pda"]
if ai_settings["automatic"]:
n_handicaps = len(game.root.get_list_property("AB", []))
MOVE_VALUE = 14 # could be rules dependent
b_stones_advantage = max(n_handicaps - 1, 0) - (cn.komi - MOVE_VALUE / 2) / MOVE_VALUE
pda = min(3, max(-3, -b_stones_advantage * (3 / 8))) # max PDA at 8 stone adv, normal 9 stone game is 8.46
handicap_analysis = request_ai_analysis(
game, cn, {"playoutDoublingAdvantage": pda, "playoutDoublingAdvantagePla": "BLACK"}
)
if not handicap_analysis:
game.katrain.log("Error getting handicap-based move", OUTPUT_ERROR)
ai_mode = AI_DEFAULT
elif ai_mode == AI_ANTIMIRROR:
antimirror_analysis = request_ai_analysis(game, cn, {"antiMirror": True})
if not antimirror_analysis:
game.katrain.log("Error getting antimirror move", OUTPUT_ERROR)
ai_mode = AI_DEFAULT
while not cn.analysis_complete:
time.sleep(0.01)
game.engines[cn.next_player].check_alive(exception_if_dead=True)
ai_thoughts = ""
if (ai_mode in AI_STRATEGIES_POLICY) and cn.policy: # pure policy based move
policy_moves = cn.policy_ranking
pass_policy = cn.policy[-1]
# dont make it jump around for the last few sensible non pass moves
top_5_pass = any([polmove[1].is_pass for polmove in policy_moves[:5]])
size = game.board_size
policy_grid = var_to_grid(cn.policy, size) # type: List[List[float]]
top_policy_move = policy_moves[0][1]
ai_thoughts += f"Using policy based strategy, base top 5 moves are {fmt_moves(policy_moves[:5])}. "
if (ai_mode == AI_POLICY and cn.depth <= ai_settings["opening_moves"]) or (
ai_mode in [AI_LOCAL, AI_TENUKI] and not (cn.move and cn.move.coords)
):
ai_mode = AI_WEIGHTED
ai_thoughts += "Strategy override, using policy-weighted strategy instead. "
ai_settings = {"pick_override": 0.9, "weaken_fac": 1, "lower_bound": 0.02}
if top_5_pass:
aimove = top_policy_move
ai_thoughts += "Playing top one because one of them is pass."
elif ai_mode == AI_POLICY:
aimove = top_policy_move
ai_thoughts += f"Playing top policy move {aimove.gtp()}."
else: # weighted or pick-based
legal_policy_moves = [(pol, mv) for pol, mv in policy_moves if not mv.is_pass and pol > 0]
board_squares = size[0] * size[1]
if ai_mode == AI_RANK: # calibrated, override from 0.8 at start to ~0.4 at full board
override = 0.8 * (1 - 0.5 * (board_squares - len(legal_policy_moves)) / board_squares)
overridetwo = 0.85 + max(0, 0.02 * (ai_settings["kyu_rank"] - 8))
else:
override = ai_settings["pick_override"]
overridetwo = 1.0
if policy_moves[0][0] > override:
aimove = top_policy_move
ai_thoughts += f"Top policy move has weight > {override:.1%}, so overriding other strategies."
elif policy_moves[0][0] + policy_moves[1][0] > overridetwo:
aimove = top_policy_move
ai_thoughts += (
f"Top two policy moves have cumulative weight > {overridetwo:.1%}, so overriding other strategies."
)
elif ai_mode == AI_WEIGHTED:
aimove, ai_thoughts = policy_weighted_move(
policy_moves, ai_settings["lower_bound"], ai_settings["weaken_fac"]
)
elif ai_mode in AI_STRATEGIES_PICK:
if ai_mode != AI_RANK:
n_moves = max(1, int(ai_settings["pick_frac"] * len(legal_policy_moves) + ai_settings["pick_n"]))
else:
orig_calib_avemodrank = 0.063015 + 0.7624 * board_squares / (
10 ** (-0.05737 * ai_settings["kyu_rank"] + 1.9482)
)
norm_leg_moves = len(legal_policy_moves) / board_squares
modified_calib_avemodrank = (
0.3931
+ 0.6559
* norm_leg_moves
* math.exp(
-1
* (
3.002 * norm_leg_moves * norm_leg_moves
- norm_leg_moves
- 0.034889 * ai_settings["kyu_rank"]
- 0.5097
)
** 2
)
- 0.01093 * ai_settings["kyu_rank"]
) * orig_calib_avemodrank
n_moves = board_squares * norm_leg_moves / (1.31165 * (modified_calib_avemodrank + 1) - 0.082653)
n_moves = max(1, round(n_moves))
if ai_mode in [AI_INFLUENCE, AI_TERRITORY, AI_LOCAL, AI_TENUKI]:
if cn.depth > ai_settings["endgame"] * board_squares:
weighted_coords = [(pol, 1, *mv.coords) for pol, mv in legal_policy_moves]
x_ai_thoughts = (
f"Generated equal weights as move number >= {ai_settings['endgame'] * size[0] * size[1]}. "
)
n_moves = int(max(n_moves, len(legal_policy_moves) // 2))
elif ai_mode in [AI_INFLUENCE, AI_TERRITORY]:
weighted_coords, x_ai_thoughts = generate_influence_territory_weights(
ai_mode, ai_settings, policy_grid, size
)
else: # ai_mode in [AI_LOCAL, AI_TENUKI]
weighted_coords, x_ai_thoughts = generate_local_tenuki_weights(
ai_mode, ai_settings, policy_grid, cn, size
)
ai_thoughts += x_ai_thoughts
else: # ai_mode in [AI_PICK, AI_RANK]:
weighted_coords = [
(policy_grid[y][x], 1, x, y)
for x in range(size[0])
for y in range(size[1])
if policy_grid[y][x] > 0
]
pick_moves = weighted_selection_without_replacement(weighted_coords, n_moves)
ai_thoughts += f"Picked {min(n_moves,len(weighted_coords))} random moves according to weights. "
if pick_moves:
new_top = [
(p, Move((x, y), player=cn.next_player)) for p, wt, x, y in heapq.nlargest(5, pick_moves)
]
aimove = new_top[0][1]
ai_thoughts += f"Top 5 among these were {fmt_moves(new_top)} and picked top {aimove.gtp()}. "
if new_top[0][0] < pass_policy:
ai_thoughts += f"But found pass ({pass_policy:.2%} to be higher rated than {aimove.gtp()} ({new_top[0][0]:.2%}) so will play top policy move instead."
aimove = top_policy_move
else:
aimove = top_policy_move
ai_thoughts += f"Pick policy strategy {ai_mode} failed to find legal moves, so is playing top policy move {aimove.gtp()}."
else:
raise ValueError(f"Unknown Policy-based AI mode {ai_mode}")
else: # Engine based move
candidate_ai_moves = cn.candidate_moves
if ai_mode == AI_HANDICAP:
candidate_ai_moves = handicap_analysis["moveInfos"]
elif ai_mode == AI_ANTIMIRROR:
candidate_ai_moves = antimirror_analysis["moveInfos"]
top_cand = Move.from_gtp(candidate_ai_moves[0]["move"], player=cn.next_player)
if top_cand.is_pass and ai_mode not in [
AI_DEFAULT,
AI_HANDICAP,
]: # don't play suicidal to balance score
aimove = top_cand
ai_thoughts += "Top move is pass, so passing regardless of strategy. "
else:
if ai_mode == AI_JIGO:
sign = cn.player_sign(cn.next_player)
jigo_move = min(
candidate_ai_moves, key=lambda move: abs(sign * move["scoreLead"] - ai_settings["target_score"])
)
aimove = Move.from_gtp(jigo_move["move"], player=cn.next_player)
ai_thoughts += f"Jigo strategy found {len(candidate_ai_moves)} candidate moves (best {top_cand.gtp()}) and chose {aimove.gtp()} as closest to 0.5 point win"
elif ai_mode == AI_SCORELOSS:
c = ai_settings["strength"]
moves = [
(
d["pointsLost"],
math.exp(min(200, -c * max(0, d["pointsLost"]))),
Move.from_gtp(d["move"], player=cn.next_player),
)
for d in candidate_ai_moves
]
topmove = weighted_selection_without_replacement(moves, 1)[0]
aimove = topmove[2]
ai_thoughts += f"ScoreLoss strategy found {len(candidate_ai_moves)} candidate moves (best {top_cand.gtp()}) and chose {aimove.gtp()} (weight {topmove[1]:.3f}, point loss {topmove[0]:.1f}) based on score weights."
elif ai_mode in [AI_SIMPLE_OWNERSHIP, AI_SETTLE_STONES]:
stones_with_player = {(*s.coords, s.player) for s in game.stones}
next_player_sign = cn.player_sign(cn.next_player)
if ai_mode == AI_SIMPLE_OWNERSHIP:
def settledness(d, player_sign, player):
return sum([abs(o) for o in d["ownership"] if player_sign * o > 0])
else:
board_size_x, board_size_y = game.board_size
def settledness(d, player_sign, player):
ownership_grid = var_to_grid(d["ownership"], (board_size_x, board_size_y))
return sum(
[abs(ownership_grid[s.coords[0]][s.coords[1]]) for s in game.stones if s.player == player]
)
def is_attachment(move):
if move.is_pass:
return False
attach_opponent_stones = sum(
(move.coords[0] + dx, move.coords[1] + dy, cn.player) in stones_with_player
for dx in [-1, 0, 1]
for dy in [-1, 0, 1]
if abs(dx) + abs(dy) == 1
)
nearby_own_stones = sum(
(move.coords[0] + dx, move.coords[1] + dy, cn.next_player) in stones_with_player
for dx in [-2, 0, 1, 2]
for dy in [-2 - 1, 0, 1, 2]
if abs(dx) + abs(dy) <= 2 # allows clamps/jumps
)
return attach_opponent_stones >= 1 and nearby_own_stones == 0
def is_tenuki(d):
return not d.is_pass and not any(
not node
or not node.move
or node.move.is_pass
or max(abs(last_c - cand_c) for last_c, cand_c in zip(node.move.coords, d.coords)) < 5
for node in [cn, cn.parent]
)
moves_with_settledness = sorted(
[
(
move,
settledness(d, next_player_sign, cn.next_player),
settledness(d, -next_player_sign, cn.player),
is_attachment(move),
is_tenuki(move),
d,
)
for d in candidate_ai_moves
if d["pointsLost"] < ai_settings["max_points_lost"]
and "ownership" in d
and (d["order"] <= 1 or d["visits"] >= ai_settings.get("min_visits", 1))
for move in [Move.from_gtp(d["move"], player=cn.next_player)]
if not (move.is_pass and d["pointsLost"] > 0.75)
],
key=lambda t: t[5]["pointsLost"]
+ ai_settings["attach_penalty"] * t[3]
+ ai_settings["tenuki_penalty"] * t[4]
- ai_settings["settled_weight"] * (t[1] + ai_settings["opponent_fac"] * t[2]),
)
if moves_with_settledness:
cands = [
f"{move.gtp()} ({d['pointsLost']:.1f} pt lost, {d['visits']} visits, {settled:.1f} settledness, {oppsettled:.1f} opponent settledness{', attachment' if isattach else ''}{', tenuki' if istenuki else ''})"
for move, settled, oppsettled, isattach, istenuki, d in moves_with_settledness[:5]
]
ai_thoughts += f"{ai_mode} strategy. Top 5 Candidates {', '.join(cands)} "
aimove = moves_with_settledness[0][0]
else:
raise (Exception("No moves found - are you using an older KataGo with no per-move ownership info?"))
else:
if ai_mode not in [AI_DEFAULT, AI_HANDICAP, AI_ANTIMIRROR]:
game.katrain.log(f"Unknown AI mode {ai_mode} or policy missing, using default.", OUTPUT_INFO)
ai_thoughts += f"Strategy {ai_mode} not found or unexpected fallback."
aimove = top_cand
if ai_mode == AI_HANDICAP:
ai_thoughts += f"Handicap strategy found {len(candidate_ai_moves)} moves returned from the engine and chose {aimove.gtp()} as top move. PDA based score {cn.format_score(handicap_analysis['rootInfo']['scoreLead'])} and win rate {cn.format_winrate(handicap_analysis['rootInfo']['winrate'])}"
if ai_mode == AI_ANTIMIRROR:
ai_thoughts += f"AntiMirror strategy found {len(candidate_ai_moves)} moves returned from the engine and chose {aimove.gtp()} as top move. antiMirror based score {cn.format_score(antimirror_analysis['rootInfo']['scoreLead'])} and win rate {cn.format_winrate(antimirror_analysis['rootInfo']['winrate'])}"
else:
ai_thoughts += f"Default strategy found {len(candidate_ai_moves)} moves returned from the engine and chose {aimove.gtp()} as top move"
game.katrain.log(f"AI thoughts: {ai_thoughts}", OUTPUT_DEBUG)
played_node = game.play(aimove)
played_node.ai_thoughts = ai_thoughts
return aimove, played_node | null |
160,865 | import os
import shutil
import sys
from kivy import Config
from kivy.storage.jsonstore import JsonStore
from katrain.core.ai import ai_rank_estimation
from katrain.core.constants import (
PLAYER_HUMAN,
PLAYER_AI,
PLAYING_NORMAL,
PLAYING_TEACHING,
OUTPUT_INFO,
OUTPUT_ERROR,
OUTPUT_DEBUG,
AI_DEFAULT,
CONFIG_MIN_VERSION,
DATA_FOLDER,
)
from katrain.core.utils import find_package_resource
def parse_version(s):
parts = [int(p) for p in s.split(".")]
while len(parts) < 3:
parts.append(0)
return parts | null |
160,866 | import base64
import copy
import gzip
import json
import random
from typing import Dict, List, Optional, Tuple
from katrain.core.constants import (
ANALYSIS_FORMAT_VERSION,
PROGRAM_NAME,
REPORT_DT,
SGF_INTERNAL_COMMENTS_MARKER,
SGF_SEPARATOR_MARKER,
VERSION,
PRIORITY_DEFAULT,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.lang import i18n
from katrain.core.sgf_parser import Move, SGFNode
from katrain.core.utils import evaluation_class, pack_floats, unpack_floats, var_to_grid
from katrain.gui.theme import Theme
def pack_floats(float_list):
if float_list is None:
return b""
return struct.pack(f"{len(float_list)}e", *float_list)
def analysis_dumps(analysis):
analysis = copy.deepcopy(analysis)
for movedict in analysis["moves"].values():
if "ownership" in movedict: # per-move ownership rarely used
del movedict["ownership"]
ownership_data = pack_floats(analysis.pop("ownership"))
policy_data = pack_floats(analysis.pop("policy"))
main_data = json.dumps(analysis).encode("utf-8")
return [
base64.standard_b64encode(gzip.compress(data)).decode("utf-8")
for data in [ownership_data, policy_data, main_data]
] | null |
160,867 | from katrain.core.game_node import GameNode
from katrain.core.sgf_parser import Move
def katrain_sgf_from_ijs(ijs, isize, jsize, player):
return [Move((j, i)).sgf((jsize, isize)) for i, j in ijs]
def tsumego_frame(bw_board, komi, black_to_play_p, ko_p, margin):
stones = stones_from_bw_board(bw_board)
filled_stones = tsumego_frame_stones(stones, komi, black_to_play_p, ko_p, margin)
region_pos = pick_all(filled_stones, "tsumego_frame_region_mark")
bw = pick_all(filled_stones, "tsumego_frame")
blacks = [(i, j) for i, j, black in bw if black]
whites = [(i, j) for i, j, black in bw if not black]
return (blacks, whites, get_analysis_region(region_pos))
def ij_sizes(stones):
return (len(stones), len(stones[0]))
class GameNode(SGFNode):
"""Represents a single game node, with one or more moves and placements."""
def __init__(self, parent=None, properties=None, move=None):
super().__init__(parent=parent, properties=properties, move=move)
self.auto_undo = None # None = not analyzed. False: not undone (good move). True: undone (bad move)
self.played_mistake_sound = None
self.ai_thoughts = ""
self.note = ""
self.move_number = 0
self.time_used = 0
self.undo_threshold = random.random() # for fractional undos
self.end_state = None
self.shortcuts_to = []
self.shortcut_from = None
self.analysis_from_sgf = None
self.clear_analysis()
def add_shortcut(self, to_node): # collapses the branch between them
nodes = [to_node]
while nodes[-1].parent and nodes[-1] != self: # ensure on path
nodes.append(nodes[-1].parent)
if nodes[-1] == self and len(nodes) > 2:
via = nodes[-2]
self.shortcuts_to.append((to_node, via)) # and first child
to_node.shortcut_from = self
def remove_shortcut(self):
from_node = self.shortcut_from
if from_node:
from_node.shortcuts_to = [(m, v) for m, v in from_node.shortcuts_to if m != self]
self.shortcut_from = None
def load_analysis(self):
if not self.analysis_from_sgf:
return False
try:
szx, szy = self.root.board_size
board_squares = szx * szy
version = self.root.get_property("KTV", ANALYSIS_FORMAT_VERSION)
if version > ANALYSIS_FORMAT_VERSION:
raise ValueError(f"Can not decode analysis data with version {version}, please update {PROGRAM_NAME}")
ownership_data, policy_data, main_data, *_ = [
gzip.decompress(base64.standard_b64decode(data)) for data in self.analysis_from_sgf
]
self.analysis = {
**json.loads(main_data),
"policy": unpack_floats(policy_data, board_squares + 1),
"ownership": unpack_floats(ownership_data, board_squares),
}
return True
except Exception as e:
print(f"Error in loading analysis: {e}")
return False
def add_list_property(self, property: str, values: List):
if property == "KT":
self.analysis_from_sgf = values
elif property == "C":
comments = [ # strip out all previously auto generated comments
c
for v in values
for c in v.split(SGF_SEPARATOR_MARKER)
if c.strip() and SGF_INTERNAL_COMMENTS_MARKER not in c
]
self.note = "".join(comments).strip() # no super call intended, just save as note to be editable
else:
return super().add_list_property(property, values)
def clear_analysis(self):
self.analysis_visits_requested = 0
self.analysis = {"moves": {}, "root": None, "ownership": None, "policy": None, "completed": False}
def sgf_properties(
self,
save_comments_player=None,
save_comments_class=None,
eval_thresholds=None,
save_analysis=False,
save_marks=False,
):
properties = copy.copy(super().sgf_properties())
note = self.note.strip()
if save_analysis and self.analysis_complete:
try:
properties["KT"] = analysis_dumps(self.analysis)
except Exception as e:
print(f"Error in saving analysis: {e}")
if self.points_lost and save_comments_class is not None and eval_thresholds is not None:
show_class = save_comments_class[evaluation_class(self.points_lost, eval_thresholds)]
else:
show_class = False
comments = properties.get("C", [])
if (
self.parent
and self.parent.analysis_exists
and self.analysis_exists
and (note or ((save_comments_player or {}).get(self.player, False) and show_class))
):
if save_marks:
candidate_moves = self.parent.candidate_moves
top_x = Move.from_gtp(candidate_moves[0]["move"]).sgf(self.board_size)
best_sq = [
Move.from_gtp(d["move"]).sgf(self.board_size)
for d in candidate_moves
if d["pointsLost"] <= 0.5 and d["move"] != "pass" and d["order"] != 0
]
if best_sq and "SQ" not in properties:
properties["SQ"] = best_sq
if top_x and "MA" not in properties:
properties["MA"] = [top_x]
comments.append("\n" + self.comment(sgf=True, interactive=False) + SGF_INTERNAL_COMMENTS_MARKER)
if self.is_root:
if save_marks:
comments = [i18n._("SGF start message") + SGF_INTERNAL_COMMENTS_MARKER + "\n"]
else:
comments = []
comments += [
*comments,
f"\nSGF generated by {PROGRAM_NAME} {VERSION}{SGF_INTERNAL_COMMENTS_MARKER}\n",
]
properties["CA"] = ["UTF-8"]
properties["AP"] = [f"{PROGRAM_NAME}:{VERSION}"]
properties["KTV"] = [ANALYSIS_FORMAT_VERSION]
if self.shortcut_from:
properties["KTSF"] = [id(self.shortcut_from)]
elif "KTSF" in properties:
del properties["KTSF"]
if self.shortcuts_to:
properties["KTSID"] = [id(self)]
elif "KTSID" in properties:
del properties["KTSID"]
if note:
comments.insert(0, f"{self.note}\n") # user notes at top!
if comments:
properties["C"] = [SGF_SEPARATOR_MARKER.join(comments).strip("\n")]
elif "C" in properties:
del properties["C"]
return properties
def order_children(children):
return sorted(
children, key=lambda c: 0.5 if c.auto_undo is None else int(c.auto_undo)
) # analyzed/not undone main, non-teach second, undone last
# various analysis functions
def analyze(
self,
engine,
priority=PRIORITY_DEFAULT,
visits=None,
ponder=False,
time_limit=True,
refine_move=None,
analyze_fast=False,
find_alternatives=False,
region_of_interest=None,
report_every=REPORT_DT,
):
engine.request_analysis(
self,
callback=lambda result, partial_result: self.set_analysis(
result, refine_move, find_alternatives, region_of_interest, partial_result
),
priority=priority,
visits=visits,
ponder=ponder,
analyze_fast=analyze_fast,
time_limit=time_limit,
next_move=refine_move,
find_alternatives=find_alternatives,
region_of_interest=region_of_interest,
report_every=report_every,
)
def update_move_analysis(self, move_analysis, move_gtp):
cur = self.analysis["moves"].get(move_gtp)
if cur is None:
self.analysis["moves"][move_gtp] = {
"move": move_gtp,
"order": ADDITIONAL_MOVE_ORDER,
**move_analysis,
} # some default values for keys missing in rootInfo
else:
cur["order"] = min(
cur["order"], move_analysis.get("order", ADDITIONAL_MOVE_ORDER)
) # parent arriving after child
if cur["visits"] < move_analysis["visits"]:
cur.update(move_analysis)
else: # prior etc only
cur.update({k: v for k, v in move_analysis.items() if k not in cur})
def set_analysis(
self,
analysis_json: Dict,
refine_move: Optional[Move] = None,
additional_moves: bool = False,
region_of_interest=None,
partial_result: bool = False,
):
if refine_move:
pvtail = analysis_json["moveInfos"][0]["pv"] if analysis_json["moveInfos"] else []
self.update_move_analysis(
{"pv": [refine_move.gtp()] + pvtail, **analysis_json["rootInfo"]}, refine_move.gtp()
)
else:
if additional_moves: # additional moves: old order matters, ignore new order
for m in analysis_json["moveInfos"]:
del m["order"]
elif refine_move is None: # normal update: old moves to end, new order matters. also for region?
for move_dict in self.analysis["moves"].values():
move_dict["order"] = ADDITIONAL_MOVE_ORDER # old moves to end
for move_analysis in analysis_json["moveInfos"]:
self.update_move_analysis(move_analysis, move_analysis["move"])
self.analysis["ownership"] = analysis_json.get("ownership")
self.analysis["policy"] = analysis_json.get("policy")
if not additional_moves and not region_of_interest:
self.analysis["root"] = analysis_json["rootInfo"]
if self.parent and self.move:
analysis_json["rootInfo"]["pv"] = [self.move.gtp()] + (
analysis_json["moveInfos"][0]["pv"] if analysis_json["moveInfos"] else []
)
self.parent.update_move_analysis(
analysis_json["rootInfo"], self.move.gtp()
) # update analysis in parent for consistency
is_normal_query = refine_move is None and not additional_moves
self.analysis["completed"] = self.analysis["completed"] or (is_normal_query and not partial_result)
def ownership(self):
return self.analysis.get("ownership")
def policy(self):
return self.analysis.get("policy")
def analysis_exists(self):
return self.analysis["root"] is not None
def analysis_complete(self):
return self.analysis["completed"] and self.analysis["root"] is not None
def root_visits(self):
return ((self.analysis or {}).get("root") or {}).get("visits", 0)
def score(self) -> Optional[float]:
if self.analysis_exists:
return self.analysis["root"].get("scoreLead")
def format_score(self, score=None):
score = score or self.score
if score is not None:
return f"{'B' if score >= 0 else 'W'}+{abs(score):.1f}"
def winrate(self) -> Optional[float]:
if self.analysis_exists:
return self.analysis["root"].get("winrate")
def format_winrate(self, win_rate=None):
win_rate = win_rate or self.winrate
if win_rate is not None:
return f"{'B' if win_rate > 0.5 else 'W'} {max(win_rate,1-win_rate):.1%}"
def move_policy_stats(self) -> Tuple[Optional[int], float, List]:
single_move = self.move
if single_move and self.parent:
policy_ranking = self.parent.policy_ranking
if policy_ranking:
for ix, (p, m) in enumerate(policy_ranking):
if m == single_move:
return ix + 1, p, policy_ranking
return None, 0.0, []
def make_pv(self, player, pv, interactive):
pvtext = f"{player}{' '.join(pv)}"
if interactive:
pvtext = f"[u][ref={pvtext}][color={Theme.INFO_PV_COLOR}]{pvtext}[/color][/ref][/u]"
return pvtext
def comment(self, sgf=False, teach=False, details=False, interactive=True):
single_move = self.move
if not self.parent or not single_move: # root
if self.root:
rules = self.get_property("RU", "Japanese")
if isinstance(rules, str): # else katago dict
rules = i18n._(rules.lower())
return f"{i18n._('komi')}: {self.komi:.1f}\n{i18n._('ruleset')}: {rules}\n"
return ""
text = i18n._("move").format(number=self.depth) + f": {single_move.player} {single_move.gtp()}\n"
if self.analysis_exists:
score = self.score
if sgf:
text += i18n._("Info:score").format(score=self.format_score(score)) + "\n"
text += i18n._("Info:winrate").format(winrate=self.format_winrate()) + "\n"
if self.parent and self.parent.analysis_exists:
previous_top_move = self.parent.candidate_moves[0]
if sgf or details:
if previous_top_move["move"] != single_move.gtp():
points_lost = self.points_lost
if sgf and points_lost > 0.5:
text += i18n._("Info:point loss").format(points_lost=points_lost) + "\n"
top_move = previous_top_move["move"]
score = self.format_score(previous_top_move["scoreLead"])
text += (
i18n._("Info:top move").format(
top_move=top_move,
score=score,
)
+ "\n"
)
else:
text += i18n._("Info:best move") + "\n"
if previous_top_move.get("pv") and (sgf or details):
pv = self.make_pv(single_move.player, previous_top_move["pv"], interactive)
text += i18n._("Info:PV").format(pv=pv) + "\n"
if sgf or details or teach:
currmove_pol_rank, currmove_pol_prob, policy_ranking = self.move_policy_stats()
if currmove_pol_rank is not None:
policy_rank_msg = i18n._("Info:policy rank")
text += policy_rank_msg.format(rank=currmove_pol_rank, probability=currmove_pol_prob) + "\n"
if currmove_pol_rank != 1 and policy_ranking and (sgf or details):
policy_best_msg = i18n._("Info:policy best")
pol_move, pol_prob = policy_ranking[0][1].gtp(), policy_ranking[0][0]
text += policy_best_msg.format(move=pol_move, probability=pol_prob) + "\n"
if self.auto_undo and sgf:
text += i18n._("Info:teaching undo") + "\n"
top_pv = self.analysis_exists and self.candidate_moves[0].get("pv")
if top_pv:
text += i18n._("Info:undo predicted PV").format(pv=f"{self.next_player}{' '.join(top_pv)}") + "\n"
else:
text = i18n._("No analysis available") if sgf else i18n._("Analyzing move...")
if self.ai_thoughts and (sgf or details):
text += "\n" + i18n._("Info:AI thoughts").format(thoughts=self.ai_thoughts)
if "C" in self.properties:
text += "\n[u]SGF Comments:[/u]\n" + "\n".join(self.properties["C"])
return text
def points_lost(self) -> Optional[float]:
single_move = self.move
if single_move and self.parent and self.analysis_exists and self.parent.analysis_exists:
parent_score = self.parent.score
score = self.score
return self.player_sign(single_move.player) * (parent_score - score)
def parent_realized_points_lost(self) -> Optional[float]:
single_move = self.move
if (
single_move
and self.parent
and self.parent.parent
and self.analysis_exists
and self.parent.parent.analysis_exists
):
parent_parent_score = self.parent.parent.score
score = self.score
return self.player_sign(single_move.player) * (score - parent_parent_score)
def player_sign(player):
return {"B": 1, "W": -1, None: 0}[player]
def candidate_moves(self) -> List[Dict]:
if not self.analysis_exists:
return []
if not self.analysis["moves"]:
polmoves = self.policy_ranking
top_polmove = polmoves[0][1] if polmoves else Move(None) # if no info at all, pass
return [
{
**self.analysis["root"],
"pointsLost": 0,
"winrateLost": 0,
"order": 0,
"move": top_polmove.gtp(),
"pv": [top_polmove.gtp()],
}
] # single visit -> go by policy/root
root_score = self.analysis["root"]["scoreLead"]
root_winrate = self.analysis["root"]["winrate"]
move_dicts = list(self.analysis["moves"].values()) # prevent incoming analysis from causing crash
top_move = [d for d in move_dicts if d["order"] == 0]
top_score_lead = top_move[0]["scoreLead"] if top_move else root_score
return sorted(
[
{
"pointsLost": self.player_sign(self.next_player) * (root_score - d["scoreLead"]),
"relativePointsLost": self.player_sign(self.next_player) * (top_score_lead - d["scoreLead"]),
"winrateLost": self.player_sign(self.next_player) * (root_winrate - d["winrate"]),
**d,
}
for d in move_dicts
],
key=lambda d: (d["order"], d["pointsLost"]),
)
def policy_ranking(self) -> Optional[List[Tuple[float, Move]]]: # return moves from highest policy value to lowest
if self.policy:
szx, szy = self.board_size
policy_grid = var_to_grid(self.policy, size=(szx, szy))
moves = [(policy_grid[y][x], Move((x, y), player=self.next_player)) for x in range(szx) for y in range(szy)]
moves.append((self.policy[-1], Move(None, player=self.next_player)))
return sorted(moves, key=lambda mp: -mp[0])
def tsumego_frame_from_katrain_game(game, komi, black_to_play_p, ko_p, margin):
current_node = game.current_node
bw_board = [[game.chains[c][0].player if c >= 0 else "-" for c in line] for line in game.board]
isize, jsize = ij_sizes(bw_board)
blacks, whites, analysis_region = tsumego_frame(bw_board, komi, black_to_play_p, ko_p, margin)
sgf_blacks = katrain_sgf_from_ijs(blacks, isize, jsize, "B")
sgf_whites = katrain_sgf_from_ijs(whites, isize, jsize, "W")
played_node = GameNode(parent=current_node, properties={"AB": sgf_blacks, "AW": sgf_whites}) # this inserts
katrain_region = analysis_region and (analysis_region[1], analysis_region[0])
return (played_node, katrain_region) | null |
160,868 | import gettext
import os
import sys
from kivy._event import Observable
from katrain.core.utils import find_package_resource
from katrain.gui.theme import Theme
i18n = Lang(DEFAULT_LANGUAGE)
def rank_label(rank):
if rank is None:
return "??k"
if rank >= 0.5:
return f"{rank:.0f}{i18n._('strength:dan')}"
else:
return f"{1-rank:.0f}{i18n._('strength:kyu')}" | null |
160,869 | import os
import sys
from kivy.utils import platform as kivy_platform
import kivy
from katrain.core.utils import find_package_resource, PATHS
from kivy.config import Config
import re
import signal
import json
import threading
import traceback
from queue import Queue
import urllib3
import webbrowser
import time
import random
import glob
from kivy.base import ExceptionHandler, ExceptionManager
from kivy.app import App
from kivy.core.clipboard import Clipboard
from kivy.lang import Builder
from kivy.resources import resource_add_path
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import Screen
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.resources import resource_find
from kivy.properties import NumericProperty, ObjectProperty, StringProperty
from kivy.clock import Clock
from kivy.metrics import dp
from katrain.core.ai import generate_ai_move
from katrain.core.lang import DEFAULT_LANGUAGE, i18n
from katrain.core.constants import (
OUTPUT_ERROR,
OUTPUT_KATAGO_STDERR,
OUTPUT_INFO,
OUTPUT_DEBUG,
OUTPUT_EXTRA_DEBUG,
MODE_ANALYZE,
HOMEPAGE,
VERSION,
STATUS_ERROR,
STATUS_INFO,
PLAYING_NORMAL,
PLAYER_HUMAN,
SGF_INTERNAL_COMMENTS_MARKER,
MODE_PLAY,
DATA_FOLDER,
AI_DEFAULT,
)
from katrain.gui.popups import (
ConfigTeacherPopup,
ConfigTimerPopup,
I18NPopup,
SaveSGFPopup,
ContributePopup,
EngineRecoveryPopup,
)
from katrain.gui.sound import play_sound
from katrain.core.base_katrain import KaTrainBase
from katrain.core.engine import KataGoEngine
from katrain.core.contribute_engine import KataGoContributeEngine
from katrain.core.game import Game, IllegalMoveException, KaTrainSGF, BaseGame
from katrain.core.sgf_parser import Move, ParseError
from katrain.gui.popups import ConfigPopup, LoadSGFPopup, NewGamePopup, ConfigAIPopup
from katrain.gui.theme import Theme
from kivymd.app import MDApp
from katrain.gui.kivyutils import *
from katrain.gui.widgets import MoveTree, I18NFileBrowser, SelectionSlider, ScoreGraph
from katrain.gui.badukpan import AnalysisControls, BadukPanControls, BadukPanWidget
from katrain.gui.controlspanel import ControlsPanel
class KaTrainApp(MDApp):
gui = ObjectProperty(None)
language = StringProperty(DEFAULT_LANGUAGE)
def __init__(self):
super().__init__()
def build(self):
self.icon = ICON # how you're supposed to set an icon
self.title = f"KaTrain v{VERSION}"
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "Gray"
self.theme_cls.primary_hue = "200"
kv_file = find_package_resource("katrain/gui.kv")
popup_kv_file = find_package_resource("katrain/popups.kv")
resource_add_path(PATHS["PACKAGE"] + "/fonts")
resource_add_path(PATHS["PACKAGE"] + "/sounds")
resource_add_path(PATHS["PACKAGE"] + "/img")
resource_add_path(os.path.abspath(os.path.expanduser(DATA_FOLDER))) # prefer resources in .katrain
theme_files = glob.glob(os.path.join(os.path.expanduser(DATA_FOLDER), "theme*.json"))
for theme_file in sorted(theme_files):
try:
with open(theme_file) as f:
theme_overrides = json.load(f)
for k, v in theme_overrides.items():
setattr(Theme, k, v)
print(f"[{theme_file}] Found theme override {k} = {v}")
except Exception as e: # noqa E722
print(f"Failed to load theme file {theme_file}: {e}")
Theme.DEFAULT_FONT = resource_find(Theme.DEFAULT_FONT)
Builder.load_file(kv_file)
Window.bind(on_request_close=self.on_request_close)
Window.bind(on_dropfile=lambda win, file: self.gui.load_sgf_file(file.decode("utf8")))
self.gui = KaTrainGui()
Builder.load_file(popup_kv_file)
win_left = win_top = win_size = None
if self.gui.config("ui_state/restoresize", True):
win_size = self.gui.config("ui_state/size", [])
win_left = self.gui.config("ui_state/left", None)
win_top = self.gui.config("ui_state/top", None)
if not win_size:
window_scale_fac = 1
try:
from screeninfo import get_monitors
for m in get_monitors():
window_scale_fac = min(window_scale_fac, (m.height - 100) / 1000, (m.width - 100) / 1300)
except Exception as e:
window_scale_fac = 0.85
win_size = [1300 * window_scale_fac, 1000 * window_scale_fac]
self.gui.log(f"Setting window size to {win_size} and position to {[win_left, win_top]}", OUTPUT_DEBUG)
Window.size = (win_size[0], win_size[1])
if win_left is not None and win_top is not None:
Window.left = win_left
Window.top = win_top
return self.gui
def on_language(self, _instance, language):
self.gui.log(f"Switching language to {language}", OUTPUT_INFO)
i18n.switch_lang(language)
self.gui._config["general"]["lang"] = language
self.gui.save_config()
if self.gui.game:
self.gui.update_state()
self.gui.controls.set_status("", STATUS_INFO)
def webbrowser(self, site_key):
websites = {
"homepage": HOMEPAGE + "#manual",
"support": HOMEPAGE + "#support",
"contribute:signup": "http://katagotraining.org/accounts/signup/",
"engine:help": HOMEPAGE + "/blob/master/ENGINE.md",
}
if site_key in websites:
webbrowser.open(websites[site_key])
def on_start(self):
self.language = self.gui.config("general/lang")
self.gui.start()
def on_request_close(self, *_args, source=None):
if source == "keyboard":
return True # do not close on esc
if getattr(self, "gui", None):
self.gui.play_mode.save_ui_state()
self.gui._config["ui_state"]["size"] = list(Window._size)
self.gui._config["ui_state"]["top"] = Window.top
self.gui._config["ui_state"]["left"] = Window.left
self.gui.save_config("ui_state")
if self.gui.engine:
self.gui.engine.shutdown(finish=None)
def signal_handler(self, _signal, _frame):
if self.gui.debug_level >= OUTPUT_DEBUG:
print("TRACEBACKS")
for threadId, stack in sys._current_frames().items():
print(f"\n# ThreadID: {threadId}")
for filename, lineno, name, line in traceback.extract_stack(stack):
print(f"\tFile: {filename}, line {lineno}, in {name}")
if line:
print(f"\t\t{line.strip()}")
self.stop()
OUTPUT_ERROR = -1
def run_app():
class CrashHandler(ExceptionHandler):
def handle_exception(self, inst):
ex_type, ex, tb = sys.exc_info()
trace = "".join(traceback.format_tb(tb))
app = MDApp.get_running_app()
if app and app.gui:
app.gui.log(
f"Exception {inst.__class__.__name__}: {', '.join(repr(a) for a in inst.args)}\n{trace}",
OUTPUT_ERROR,
)
else:
print(f"Exception {inst.__class__}: {inst.args}\n{trace}")
return ExceptionManager.PASS
ExceptionManager.add_handler(CrashHandler())
app = KaTrainApp()
signal.signal(signal.SIGINT, app.signal_handler)
app.run() | null |
160,870 | import glob
import json
import os
import re
import stat
import threading
import time
from typing import Any, Dict, List, Tuple, Union
from zipfile import ZipFile
import urllib3
from kivy.clock import Clock
from kivy.metrics import dp
from kivy.properties import BooleanProperty, ListProperty, NumericProperty, ObjectProperty, StringProperty
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.utils import platform
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.uix.textfield import MDTextField
from katrain.core.ai import ai_rank_estimation, game_report
from katrain.core.constants import (
AI_CONFIG_DEFAULT,
AI_DEFAULT,
AI_KEY_PROPERTIES,
AI_OPTION_VALUES,
AI_STRATEGIES_RECOMMENDED_ORDER,
DATA_FOLDER,
OUTPUT_DEBUG,
OUTPUT_ERROR,
OUTPUT_INFO,
SGF_INTERNAL_COMMENTS_MARKER,
STATUS_INFO,
PLAYER_HUMAN,
ADDITIONAL_MOVE_ORDER,
)
from katrain.core.engine import KataGoEngine
from katrain.core.lang import i18n, rank_label
from katrain.core.sgf_parser import Move
from katrain.core.utils import PATHS, find_package_resource, evaluation_class
from katrain.gui.kivyutils import (
BackgroundMixin,
I18NSpinner,
BackgroundLabel,
TableHeaderLabel,
TableCellLabel,
TableStatLabel,
PlayerInfo,
SizedRectangleButton,
AutoSizedRectangleButton,
)
from katrain.gui.theme import Theme
from katrain.gui.widgets.progress_loader import ProgressLoader
def wrap_anchor(widget):
anchor = AnchorLayout()
anchor.add_widget(widget)
return anchor | null |
160,871 | from kivy.clock import Clock
from kivymd.app import MDApp
from kivy.core.audio import SoundLoader
from kivy.utils import platform
cached_sounds = {}
try:
SoundLoader._classes.sort(key=lambda cls: [v for k, v in ranking if k in cls.__name__.lower()][0])
except Exception as e:
print("Exception sorting sound loaders: ", e) # private vars, so could break with versions etc
def play_sound(file, volume=1, cache=True):
def _play(sound):
if sound:
sound.play()
sound.seek(0)
app = MDApp.get_running_app()
if app and app.gui and app.gui.config("timer/sound"):
sound = cached_sounds.get(file)
if sound is None:
sound = SoundLoader.load(file)
if cache:
cached_sounds[file] = sound
if sound is not None:
sound.volume = volume
Clock.schedule_once(lambda _dt: _play(sound), 0) | null |
160,872 | from kivy.clock import Clock
from kivymd.app import MDApp
from kivy.core.audio import SoundLoader
from kivy.utils import platform
cached_sounds = {}
def stop_sound(file):
sound = cached_sounds.get(file)
if sound:
sound.stop() | null |
160,873 | import string
from functools import partial
from os import walk
from os.path import dirname, expanduser, getmtime, isdir, isfile, join, sep
from kivy import Config
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, OptionProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.filechooser import FileChooserListLayout, FileChooserListView
from kivy.uix.treeview import TreeView, TreeViewLabel
from kivy.utils import platform
from katrain.gui.theme import Theme
def last_modified_first(files, filesystem):
return sorted(f for f in files if filesystem.is_dir(f)) + sorted(
[f for f in files if not filesystem.is_dir(f)], key=lambda f: -getmtime(f)
) | null |
160,874 | import string
from functools import partial
from os import walk
from os.path import dirname, expanduser, getmtime, isdir, isfile, join, sep
from kivy import Config
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, OptionProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.filechooser import FileChooserListLayout, FileChooserListView
from kivy.uix.treeview import TreeView, TreeViewLabel
from kivy.utils import platform
from katrain.gui.theme import Theme
if platform == "win":
from ctypes import windll, create_unicode_buffer
def get_home_directory():
if platform == "win":
user_path = expanduser("~")
if not isdir(join(user_path, "Desktop")):
user_path = dirname(user_path)
else:
user_path = expanduser("~")
return user_path | null |
160,875 | import string
from functools import partial
from os import walk
from os.path import dirname, expanduser, getmtime, isdir, isfile, join, sep
from kivy import Config
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, OptionProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.filechooser import FileChooserListLayout, FileChooserListView
from kivy.uix.treeview import TreeView, TreeViewLabel
from kivy.utils import platform
from katrain.gui.theme import Theme
if platform == "win":
from ctypes import windll, create_unicode_buffer
def get_drives():
drives = []
if platform == "win":
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.ascii_uppercase:
if bitmask & 1:
name = create_unicode_buffer(64)
# get name of the drive
drive = letter + ":"
if isdir(drive):
drives.append((drive, name.value))
bitmask >>= 1
elif platform == "linux":
drives.append((sep, sep))
drives.append((expanduser("~"), "~/"))
places = (sep + "mnt", sep + "media")
for place in places:
if isdir(place):
for directory in next(walk(place))[1]:
drives.append((place + sep + directory, directory))
elif platform == "macosx" or platform == "ios":
drives.append((expanduser("~"), "~/"))
vol = sep + "Volume"
if isdir(vol):
for drive in next(walk(vol))[1]:
drives.append((vol + sep + drive, drive))
return drives | null |
160,876 |
def to_hexcol(kivycol):
return "#" + "".join(f"{round(c * 255):02x}" for c in kivycol[:3]) | null |
160,877 | from kivy.clock import Clock
from kivy.core.image import Image
from kivy.core.text import Label as CoreLabel
from kivy.core.text.markup import MarkupLabel as CoreMarkupLabel
from kivy.core.window import Window
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.properties import (
BooleanProperty,
ListProperty,
NumericProperty,
ObjectProperty,
OptionProperty,
StringProperty,
)
from kivy.resources import resource_find
from kivy.uix.behaviors import ButtonBehavior, ToggleButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.spinner import Spinner
from kivy.uix.widget import Widget
from kivymd.app import MDApp
from kivymd.uix.behaviors import CircularRippleBehavior, RectangularRippleBehavior
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import BaseFlatButton, BasePressedButton
from kivymd.uix.navigationdrawer import MDNavigationDrawer
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.uix.textfield import MDTextField
from katrain.core.constants import (
AI_STRATEGIES_RECOMMENDED_ORDER,
GAME_TYPES,
MODE_PLAY,
PLAYER_AI,
PLAYER_HUMAN,
PLAYING_NORMAL,
PLAYING_TEACHING,
)
from katrain.core.lang import i18n
from katrain.gui.theme import Theme
def cached_text_texture(text, font_name, markup, _cache={}, **kwargs):
args = (text, font_name, markup, *[(k, v) for k, v in kwargs.items()])
texture = _cache.get(args)
if texture:
return texture
label_cls = CoreMarkupLabel if markup else CoreLabel
label = label_cls(text=text, bold=True, font_name=font_name or i18n.font_name, **kwargs)
label.refresh()
texture = _cache[args] = label.texture
return texture
def draw_text(pos, text, font_name=None, markup=False, **kwargs):
texture = cached_text_texture(text, font_name, markup, **kwargs)
Rectangle(texture=texture, pos=(pos[0] - texture.size[0] / 2, pos[1] - texture.size[1] / 2), size=texture.size) | null |
160,878 | from kivy.clock import Clock
from kivy.core.image import Image
from kivy.core.text import Label as CoreLabel
from kivy.core.text.markup import MarkupLabel as CoreMarkupLabel
from kivy.core.window import Window
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.properties import (
BooleanProperty,
ListProperty,
NumericProperty,
ObjectProperty,
OptionProperty,
StringProperty,
)
from kivy.resources import resource_find
from kivy.uix.behaviors import ButtonBehavior, ToggleButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.spinner import Spinner
from kivy.uix.widget import Widget
from kivymd.app import MDApp
from kivymd.uix.behaviors import CircularRippleBehavior, RectangularRippleBehavior
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import BaseFlatButton, BasePressedButton
from kivymd.uix.navigationdrawer import MDNavigationDrawer
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.uix.textfield import MDTextField
from katrain.core.constants import (
AI_STRATEGIES_RECOMMENDED_ORDER,
GAME_TYPES,
MODE_PLAY,
PLAYER_AI,
PLAYER_HUMAN,
PLAYING_NORMAL,
PLAYING_TEACHING,
)
from katrain.core.lang import i18n
from katrain.gui.theme import Theme
def draw_circle(pos, r, col):
Color(*col)
Ellipse(pos=(pos[0] - r, pos[1] - r), size=(2 * r, 2 * r)) | null |
160,879 | from kivy.clock import Clock
from kivy.core.image import Image
from kivy.core.text import Label as CoreLabel
from kivy.core.text.markup import MarkupLabel as CoreMarkupLabel
from kivy.core.window import Window
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.properties import (
BooleanProperty,
ListProperty,
NumericProperty,
ObjectProperty,
OptionProperty,
StringProperty,
)
from kivy.resources import resource_find
from kivy.uix.behaviors import ButtonBehavior, ToggleButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.spinner import Spinner
from kivy.uix.widget import Widget
from kivymd.app import MDApp
from kivymd.uix.behaviors import CircularRippleBehavior, RectangularRippleBehavior
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.button import BaseFlatButton, BasePressedButton
from kivymd.uix.navigationdrawer import MDNavigationDrawer
from kivymd.uix.selectioncontrol import MDCheckbox
from kivymd.uix.textfield import MDTextField
from katrain.core.constants import (
AI_STRATEGIES_RECOMMENDED_ORDER,
GAME_TYPES,
MODE_PLAY,
PLAYER_AI,
PLAYER_HUMAN,
PLAYING_NORMAL,
PLAYING_TEACHING,
)
from katrain.core.lang import i18n
from katrain.gui.theme import Theme
def cached_texture(path, _cache={}):
tex = _cache.get(path)
if not tex:
tex = _cache[path] = Image(resource_find(path)).texture
return tex | null |
160,881 | from __future__ import annotations
import asyncio
import contextlib
from typing import TYPE_CHECKING, Optional, Type, TypeVar
def _typing_done_callback(fut: asyncio.Future) -> None:
# just retrieve any exception and call it a day
with contextlib.suppress(asyncio.CancelledError, Exception):
fut.exception() | null |
160,882 | from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Type
from .enums import ExpireBehaviour, try_enum
from .errors import InvalidArgument
from .user import User
from .utils import MISSING, get_as_snowflake, parse_time
class Integration:
"""Represents a guild integration.
.. versionadded:: 1.4
Attributes
----------
id: :class:`int`
The integration ID.
name: :class:`str`
The integration name.
guild: :class:`Guild`
The guild of the integration.
type: :class:`str`
The integration type (i.e. Twitch).
enabled: :class:`bool`
Whether the integration is currently enabled.
account: :class:`IntegrationAccount`
The account linked to this integration.
user: :class:`User`
The user that added this integration.
"""
__slots__ = (
"guild",
"id",
"_state",
"type",
"name",
"account",
"user",
"enabled",
)
def __init__(self, *, data: IntegrationPayload, guild: Guild) -> None:
self.guild = guild
self._state = guild._state
self._from_data(data)
def __repr__(self) -> str:
return f"<{self.__class__.__name__} id={self.id} name={self.name!r}>"
def _from_data(self, data: IntegrationPayload) -> None:
self.id: int = int(data["id"])
self.type: IntegrationType = data["type"]
self.name: str = data["name"]
self.account: IntegrationAccount = IntegrationAccount(data["account"])
user = data.get("user")
self.user = User(state=self._state, data=user) if user else None
self.enabled: bool = data["enabled"]
async def delete(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Deletes the integration.
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
Parameters
----------
reason: :class:`str`
The reason the integration was deleted. Shows up on the audit log.
.. versionadded:: 2.0
Raises
------
Forbidden
You do not have permission to delete the integration.
HTTPException
Deleting the integration failed.
"""
await self._state.http.delete_integration(self.guild.id, self.id, reason=reason)
class StreamIntegration(Integration):
"""Represents a stream integration for Twitch or YouTube.
.. versionadded:: 2.0
Attributes
----------
id: :class:`int`
The integration ID.
name: :class:`str`
The integration name.
guild: :class:`Guild`
The guild of the integration.
type: :class:`str`
The integration type (i.e. Twitch).
enabled: :class:`bool`
Whether the integration is currently enabled.
syncing: :class:`bool`
Where the integration is currently syncing.
enable_emoticons: Optional[:class:`bool`]
Whether emoticons should be synced for this integration (currently twitch only).
expire_behaviour: :class:`ExpireBehaviour`
The behaviour of expiring subscribers. Aliased to ``expire_behavior`` as well.
expire_grace_period: :class:`int`
The grace period (in days) for expiring subscribers.
user: :class:`User`
The user for the integration.
account: :class:`IntegrationAccount`
The integration account information.
synced_at: :class:`datetime.datetime`
An aware UTC datetime representing when the integration was last synced.
"""
__slots__ = (
"revoked",
"expire_behaviour",
"expire_grace_period",
"synced_at",
"_role_id",
"syncing",
"enable_emoticons",
"subscriber_count",
)
def _from_data(self, data: StreamIntegrationPayload) -> None:
super()._from_data(data)
self.revoked: bool = data["revoked"]
self.expire_behaviour: ExpireBehaviour = try_enum(ExpireBehaviour, data["expire_behavior"])
self.expire_grace_period: int = data["expire_grace_period"]
self.synced_at: datetime.datetime = parse_time(data["synced_at"])
self._role_id: Optional[int] = get_as_snowflake(data, "role_id")
self.syncing: bool = data["syncing"]
self.enable_emoticons: bool = data["enable_emoticons"]
self.subscriber_count: int = data["subscriber_count"]
def expire_behavior(self) -> ExpireBehaviour:
""":class:`ExpireBehaviour`: An alias for :attr:`expire_behaviour`."""
return self.expire_behaviour
def role(self) -> Optional[Role]:
"""Optional[:class:`Role`] The role which the integration uses for subscribers."""
return self.guild.get_role(self._role_id) # type: ignore
async def edit(
self,
*,
expire_behaviour: ExpireBehaviour = MISSING,
expire_grace_period: int = MISSING,
enable_emoticons: bool = MISSING,
) -> None:
"""|coro|
Edits the integration.
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
Parameters
----------
expire_behaviour: :class:`ExpireBehaviour`
The behaviour when an integration subscription lapses. Aliased to ``expire_behavior`` as well.
expire_grace_period: :class:`int`
The period (in days) where the integration will ignore lapsed subscriptions.
enable_emoticons: :class:`bool`
Where emoticons should be synced for this integration (currently twitch only).
Raises
------
Forbidden
You do not have permission to edit the integration.
HTTPException
Editing the guild failed.
InvalidArgument
``expire_behaviour`` did not receive a :class:`ExpireBehaviour`.
"""
payload: Dict[str, Any] = {}
if expire_behaviour is not MISSING:
if not isinstance(expire_behaviour, ExpireBehaviour):
raise InvalidArgument("expire_behaviour field must be of type ExpireBehaviour")
payload["expire_behavior"] = expire_behaviour.value
if expire_grace_period is not MISSING:
payload["expire_grace_period"] = expire_grace_period
if enable_emoticons is not MISSING:
payload["enable_emoticons"] = enable_emoticons
# This endpoint is undocumented.
# Unsure if it returns the data or not as a result
await self._state.http.edit_integration(self.guild.id, self.id, **payload)
async def sync(self) -> None:
"""|coro|
Syncs the integration.
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
Raises
------
Forbidden
You do not have permission to sync the integration.
HTTPException
Syncing the integration failed.
"""
await self._state.http.sync_integration(self.guild.id, self.id)
self.synced_at = datetime.datetime.now(datetime.timezone.utc)
class BotIntegration(Integration):
"""Represents a bot integration on discord.
.. versionadded:: 2.0
Attributes
----------
id: :class:`int`
The integration ID.
name: :class:`str`
The integration name.
guild: :class:`Guild`
The guild of the integration.
type: :class:`str`
The integration type (i.e. Twitch).
enabled: :class:`bool`
Whether the integration is currently enabled.
user: :class:`User`
The user that added this integration.
account: :class:`IntegrationAccount`
The integration account information.
application: :class:`IntegrationApplication`
The application tied to this integration.
"""
__slots__ = ("application",)
def _from_data(self, data: BotIntegrationPayload) -> None:
super()._from_data(data)
self.application = IntegrationApplication(data=data["application"], state=self._state)
class BotIntegration(BaseIntegration):
application: IntegrationApplication
def _integration_factory(value: str) -> Tuple[Type[Integration], str]:
if value == "discord":
return BotIntegration, value
if value in ("twitch", "youtube"):
return StreamIntegration, value
return Integration, value | null |
160,883 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
def unwrap_function(function: Callable[..., Any]) -> Callable[..., Any]:
partial = functools.partial
while True:
if hasattr(function, "__wrapped__"):
function = function.__wrapped__
elif isinstance(function, partial):
function = function.func
else:
return function | null |
160,884 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
class Greedy(List[T]):
r"""A special converter that greedily consumes arguments until it can't.
As a consequence of this behaviour, most input errors are silently discarded,
since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the
internal string parsing routine, and continues parsing regularly.
For example, in the following code:
.. code-block:: python3
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
An invocation of ``[p]test 1 2 3 4 5 6 hello`` would pass ``numbers`` with
``[1, 2, 3, 4, 5, 6]`` and ``reason`` with ``hello``\.
For more information, check :ref:`ext_commands_special_converters`.
"""
__slots__ = ("converter",)
def __init__(self, *, converter: T) -> None:
self.converter = converter
def __repr__(self) -> str:
converter = getattr(self.converter, "__name__", repr(self.converter))
return f"Greedy[{converter}]"
def __class_getitem__(cls, params: Union[Tuple[T], T]) -> Greedy[T]:
if not isinstance(params, tuple):
params = (params,)
if len(params) != 1:
raise TypeError("Greedy[...] only takes a single argument")
converter = params[0]
origin = getattr(converter, "__origin__", None)
args = getattr(converter, "__args__", ())
if not (callable(converter) or isinstance(converter, Converter) or origin is not None):
raise TypeError("Greedy[...] expects a type or a Converter instance.")
if converter in (str, type(None)) or origin is Greedy:
raise TypeError(f"Greedy[{converter.__class__.__name__}] is invalid.")
if origin is Union and type(None) in args:
raise TypeError(f"Greedy[{converter!r}] is invalid.")
return cls(converter=converter)
from nextcord.errors import ClientException, DiscordException
def get_signature_parameters(
function: Callable[..., Any], globalns: Dict[str, Any]
) -> Dict[str, inspect.Parameter]:
signature = inspect.signature(function)
params = {}
cache: Dict[str, Any] = {}
eval_annotation = nextcord.utils.evaluate_annotation
for name, parameter in signature.parameters.items():
annotation = parameter.annotation
if annotation is parameter.empty:
params[name] = parameter
continue
if annotation is None:
params[name] = parameter.replace(annotation=type(None))
continue
annotation = eval_annotation(annotation, globalns, globalns, cache)
if annotation is Greedy:
raise TypeError("Unparameterized Greedy[...] is disallowed in signature.")
params[name] = parameter.replace(annotation=annotation)
return params | null |
160,885 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
class CommandError(DiscordException):
r"""The base exception type for all command related errors.
This inherits from :exc:`nextcord.DiscordException`.
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from :class:`.Bot`\, :func:`.on_command_error`.
"""
def __init__(self, message: Optional[str] = None, *args: Any) -> None:
if message is not None:
# clean-up @everyone and @here mentions
m = message.replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere")
super().__init__(m, *args)
else:
super().__init__(*args)
class CommandInvokeError(CommandError):
"""Exception raised when the command being invoked raised an exception.
This inherits from :exc:`CommandError`
Attributes
----------
original: :exc:`Exception`
The original exception that was raised. You can also get this via
the ``__cause__`` attribute.
"""
def __init__(self, e: Exception) -> None:
self.original: Exception = e
super().__init__(f"Command raised an exception: {e.__class__.__name__}: {e}")
def wrap_callback(coro):
@functools.wraps(coro)
async def wrapped(*args, **kwargs):
try:
ret = await coro(*args, **kwargs)
except CommandError:
raise
except asyncio.CancelledError:
return None
except Exception as exc:
raise CommandInvokeError(exc) from exc
return ret
return wrapped | null |
160,886 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
class CommandError(DiscordException):
r"""The base exception type for all command related errors.
This inherits from :exc:`nextcord.DiscordException`.
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from :class:`.Bot`\, :func:`.on_command_error`.
"""
def __init__(self, message: Optional[str] = None, *args: Any) -> None:
if message is not None:
# clean-up @everyone and @here mentions
m = message.replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere")
super().__init__(m, *args)
else:
super().__init__(*args)
class CommandInvokeError(CommandError):
"""Exception raised when the command being invoked raised an exception.
This inherits from :exc:`CommandError`
Attributes
----------
original: :exc:`Exception`
The original exception that was raised. You can also get this via
the ``__cause__`` attribute.
"""
def __init__(self, e: Exception) -> None:
self.original: Exception = e
super().__init__(f"Command raised an exception: {e.__class__.__name__}: {e}")
def hooked_wrapped_callback(command, ctx, coro):
@functools.wraps(coro)
async def wrapped(*args, **kwargs):
try:
ret = await coro(*args, **kwargs)
except CommandError:
ctx.command_failed = True
raise
except asyncio.CancelledError:
ctx.command_failed = True
return None
except Exception as exc:
ctx.command_failed = True
raise CommandInvokeError(exc) from exc
finally:
if command._max_concurrency is not None:
await command._max_concurrency.release(ctx)
await command.call_after_hooks(ctx)
return ret
return wrapped | null |
160,887 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
CogT = TypeVar("CogT", bound="Cog")
ContextT = TypeVar("ContextT", bound="Context")
P = ParamSpec("P") if TYPE_CHECKING else TypeVar("P")
class Group(GroupMixin[CogT], Command[CogT, P, T]):
"""A class that implements a grouping protocol for commands to be
executed as subcommands.
This class is a subclass of :class:`.Command` and thus all options
valid in :class:`.Command` are valid in here as well.
Attributes
----------
invoke_without_command: :class:`bool`
Indicates if the group callback should begin parsing and
invocation only if no subcommand was found. Useful for
making it an error handling function to tell the user that
no subcommand was found or to have different functionality
in case no subcommand was found. If this is ``False``, then
the group callback will always be invoked first. This means
that the checks and the parsing dictated by its parameters
will be executed. Defaults to ``False``.
case_insensitive: :class:`bool`
Indicates if the group's commands should be case insensitive.
Defaults to ``False``.
"""
def __init__(self, *args: Any, **attrs: Any) -> None:
self.invoke_without_command: bool = attrs.pop("invoke_without_command", False)
GroupMixin.__init__(self, *args, **attrs)
Command.__init__(self, *args, **attrs)
def copy(self) -> Self:
"""Creates a copy of this :class:`Group`.
Returns
-------
:class:`Group`
A new instance of this group.
"""
ret = super().copy()
for cmd in self.commands:
ret.add_command(cmd.copy())
return ret
async def invoke(self, ctx: Context) -> None:
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
early_invoke = not self.invoke_without_command
if early_invoke:
await self.prepare(ctx)
view = ctx.view
previous = view.index
view.skip_ws()
trigger = view.get_word()
if trigger:
ctx.subcommand_passed = trigger
ctx.invoked_subcommand = self.all_commands.get(trigger, None)
if early_invoke:
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
ctx.invoked_parents.append(ctx.invoked_with) # type: ignore
if trigger and ctx.invoked_subcommand:
ctx.invoked_with = trigger
await ctx.invoked_subcommand.invoke(ctx)
elif not early_invoke:
# undo the trigger parsing
view.index = previous
view.previous = previous
await super().invoke(ctx)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.invoked_subcommand = None
early_invoke = not self.invoke_without_command
if early_invoke:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
view = ctx.view
previous = view.index
view.skip_ws()
trigger = view.get_word()
if trigger:
ctx.subcommand_passed = trigger
ctx.invoked_subcommand = self.all_commands.get(trigger, None)
if early_invoke:
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
ctx.invoked_parents.append(ctx.invoked_with) # type: ignore
if trigger and ctx.invoked_subcommand:
ctx.invoked_with = trigger
await ctx.invoked_subcommand.reinvoke(ctx, call_hooks=call_hooks)
elif not early_invoke:
# undo the trigger parsing
view.index = previous
view.previous = previous
await super().reinvoke(ctx, call_hooks=call_hooks)
Coro = Coroutine[Any, Any, T]
def group(
name: str = ...,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
Group[CogT, P, T],
]:
... | null |
160,888 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
MISSING: Any = nextcord.utils.MISSING
T = TypeVar("T")
CogT = TypeVar("CogT", bound="Cog")
ContextT = TypeVar("ContextT", bound="Context")
P = ParamSpec("P") if TYPE_CHECKING else TypeVar("P")
class Group(GroupMixin[CogT], Command[CogT, P, T]):
def __init__(self, *args: Any, **attrs: Any) -> None:
def copy(self) -> Self:
async def invoke(self, ctx: Context) -> None:
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
Coro = Coroutine[Any, Any, T]
def group(
name: str = ...,
cls: Type[Group[CogT, P, T]] = MISSING,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
Group[CogT, P, T],
]:
... | null |
160,889 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
MISSING: Any = nextcord.utils.MISSING
ContextT = TypeVar("ContextT", bound="Context")
GroupT = TypeVar("GroupT", bound="Group")
P = ParamSpec("P") if TYPE_CHECKING else TypeVar("P")
class Cog(ClientCog, metaclass=CogMeta):
"""The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to
help group commands together. More information on them can be found on
the :ref:`ext_commands_cogs` page.
When inheriting from this class, the options shown in :class:`CogMeta`
are equally valid here.
"""
__cog_name__: ClassVar[str]
__cog_settings__: ClassVar[Dict[str, Any]]
__cog_commands__: ClassVar[List[Command]]
__cog_listeners__: ClassVar[List[Tuple[str, str]]]
def __new__(cls, *_args: Any, **_kwargs: Any) -> Self:
# For issue 426, we need to store a copy of the command objects
# since we modify them to inject `self` to them.
# To do this, we need to interfere with the Cog creation process.
self = super().__new__(cls)
cmd_attrs = cls.__cog_settings__
# Either update the command with the cog provided defaults or copy it.
# r.e type ignore, type-checker complains about overriding a ClassVar
self.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in cls.__cog_commands__) # type: ignore
lookup = {cmd.qualified_name: cmd for cmd in self.__cog_commands__}
# Update the Command instances dynamically as well
for command in self.__cog_commands__:
setattr(self, command.callback.__name__, command)
parent = command.parent
if parent is not None:
# Get the latest parent reference
parent = lookup[parent.qualified_name] # type: ignore
# Update our parent's reference to our self
parent.remove_command(command.name) # type: ignore
parent.add_command(command) # type: ignore
return self
def get_commands(self) -> List[Command]:
r"""
Returns
-------
List[:class:`.Command`]
A :class:`list` of :class:`.Command`\s that are
defined inside this cog.
.. note::
This does not include subcommands.
"""
return [c for c in self.__cog_commands__ if c.parent is None]
def qualified_name(self) -> str:
""":class:`str`: Returns the cog's specified name, not the class name."""
return self.__cog_name__
def description(self) -> str:
""":class:`str`: Returns the cog's description, typically the cleaned docstring."""
return self.__cog_description__
def description(self, description: str) -> None:
self.__cog_description__ = description
def walk_commands(self) -> Generator[Command, None, None]:
"""An iterator that recursively walks through this cog's commands and subcommands.
Yields
------
Union[:class:`.Command`, :class:`.Group`]
A command or group from the cog.
"""
from .core import GroupMixin
for command in self.__cog_commands__:
if command.parent is None:
yield command
if isinstance(command, GroupMixin):
yield from command.walk_commands()
def get_listeners(self) -> List[Tuple[str, Callable[..., Any]]]:
"""Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.
Returns
-------
List[Tuple[:class:`str`, :ref:`coroutine <coroutine>`]]
The listeners defined in this cog.
"""
return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__]
def listener(cls, name: str = MISSING) -> Callable[[FuncT], FuncT]:
"""A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
----------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
------
TypeError
The function is not a coroutine function or a string was not passed as
the name.
"""
if name is not MISSING and not isinstance(name, str):
raise TypeError(
f"Cog.listener expected str but received {name.__class__.__name__!r} instead."
)
def decorator(func: FuncT) -> FuncT:
actual = func
if isinstance(actual, staticmethod):
actual = actual.__func__
if not asyncio.iscoroutinefunction(actual):
raise TypeError("Listener function must be a coroutine function.")
actual.__cog_listener__ = True
to_assign = name or actual.__name__
try:
actual.__cog_listener_names__.append(to_assign)
except AttributeError:
actual.__cog_listener_names__ = [to_assign]
# we have to return `func` instead of `actual` because
# we need the type to be `staticmethod` for the metaclass
# to pick it up but the metaclass unfurls the function and
# thus the assignments need to be on the actual function
return func
return decorator
def has_error_handler(self) -> bool:
""":class:`bool`: Checks whether the cog has an error handler.
.. versionadded:: 1.7
"""
return not hasattr(self.cog_command_error.__func__, "__cog_special_method__")
def cog_unload(self) -> None:
"""A special method that is called when the cog gets removed.
This function **cannot** be a coroutine. It must be a regular
function.
Subclasses must replace this if they want special unloading behaviour.
"""
def bot_check_once(self, ctx: Context) -> bool:
"""A special method that registers as a :meth:`.Bot.check_once`
check.
This function **can** be a coroutine and must take a sole parameter,
``ctx``, to represent the :class:`.Context`.
"""
return True
def bot_check(self, ctx: Context) -> bool:
"""A special method that registers as a :meth:`.Bot.check`
check.
This function **can** be a coroutine and must take a sole parameter,
``ctx``, to represent the :class:`.Context`.
"""
return True
def cog_check(self, ctx: Context) -> bool:
"""A special method that registers as a :func:`~nextcord.ext.commands.check`
for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter,
``ctx``, to represent the :class:`.Context`.
"""
return True
async def cog_command_error(self, ctx: Context, error: Exception) -> None:
"""A special method that is called whenever an error
is dispatched inside this cog.
This is similar to :func:`.on_command_error` except only applying
to the commands inside this cog.
This **must** be a coroutine.
.. note::
This is only called for prefix commands.
Parameters
----------
ctx: :class:`.Context`
The invocation context where the error happened.
error: :class:`CommandError`
The error that happened.
"""
async def cog_before_invoke(self, ctx: Context) -> None:
"""A special method that acts as a cog local pre-invoke hook.
This is similar to :meth:`.Command.before_invoke`.
This **must** be a coroutine.
Parameters
----------
ctx: :class:`.Context`
The invocation context.
"""
async def cog_after_invoke(self, ctx: Context) -> None:
"""A special method that acts as a cog local post-invoke hook.
This is similar to :meth:`.Command.after_invoke`.
This **must** be a coroutine.
Parameters
----------
ctx: :class:`.Context`
The invocation context.
"""
def _inject(self, bot: BotBase) -> Self:
cls = self.__class__
# realistically, the only thing that can cause loading errors
# is essentially just the command loading, which raises if there are
# duplicates. When this condition is met, we want to undo all what
# we've added so far for some form of atomic loading.
for index, command in enumerate(self.__cog_commands__):
command.cog = self
if command.parent is None:
try:
bot.add_command(command)
except Exception as e:
# undo our additions
for to_undo in self.__cog_commands__[:index]:
if to_undo.parent is None:
bot.remove_command(to_undo.name)
raise e
# check if we're overriding the default
if cls.bot_check is not Cog.bot_check:
bot.add_check(self.bot_check)
if cls.bot_check_once is not Cog.bot_check_once:
bot.add_check(self.bot_check_once, call_once=True)
# while Bot.add_listener can raise if it's not a coroutine,
# this precondition is already met by the listener decorator
# already, thus this should never raise.
# Outside of, memory errors and the like...
for name, method_name in self.__cog_listeners__:
bot.add_listener(getattr(self, method_name), name)
return self
def _eject(self, bot: BotBase) -> None:
cls = self.__class__
try:
for command in self.__cog_commands__:
if command.parent is None:
bot.remove_command(command.name)
for _, method_name in self.__cog_listeners__:
bot.remove_listener(getattr(self, method_name))
if cls.bot_check is not Cog.bot_check:
bot.remove_check(self.bot_check)
if cls.bot_check_once is not Cog.bot_check_once:
bot.remove_check(self.bot_check_once, call_once=True)
finally:
with contextlib.suppress(Exception):
self.cog_unload()
Coro = Coroutine[Any, Any, T]
def group(
name: str = ...,
cls: Type[GroupT] = MISSING,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[Cog, ContextT, P], Coro[Any]],
Callable[Concatenate[ContextT, P], Coro[Any]],
]
],
GroupT,
]:
... | null |
160,890 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
MISSING: Any = nextcord.utils.MISSING
T = TypeVar("T")
CogT = TypeVar("CogT", bound="Cog")
ContextT = TypeVar("ContextT", bound="Context")
GroupT = TypeVar("GroupT", bound="Group")
P = ParamSpec("P") if TYPE_CHECKING else TypeVar("P")
class Group(GroupMixin[CogT], Command[CogT, P, T]):
"""A class that implements a grouping protocol for commands to be
executed as subcommands.
This class is a subclass of :class:`.Command` and thus all options
valid in :class:`.Command` are valid in here as well.
Attributes
----------
invoke_without_command: :class:`bool`
Indicates if the group callback should begin parsing and
invocation only if no subcommand was found. Useful for
making it an error handling function to tell the user that
no subcommand was found or to have different functionality
in case no subcommand was found. If this is ``False``, then
the group callback will always be invoked first. This means
that the checks and the parsing dictated by its parameters
will be executed. Defaults to ``False``.
case_insensitive: :class:`bool`
Indicates if the group's commands should be case insensitive.
Defaults to ``False``.
"""
def __init__(self, *args: Any, **attrs: Any) -> None:
self.invoke_without_command: bool = attrs.pop("invoke_without_command", False)
GroupMixin.__init__(self, *args, **attrs)
Command.__init__(self, *args, **attrs)
def copy(self) -> Self:
"""Creates a copy of this :class:`Group`.
Returns
-------
:class:`Group`
A new instance of this group.
"""
ret = super().copy()
for cmd in self.commands:
ret.add_command(cmd.copy())
return ret
async def invoke(self, ctx: Context) -> None:
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
early_invoke = not self.invoke_without_command
if early_invoke:
await self.prepare(ctx)
view = ctx.view
previous = view.index
view.skip_ws()
trigger = view.get_word()
if trigger:
ctx.subcommand_passed = trigger
ctx.invoked_subcommand = self.all_commands.get(trigger, None)
if early_invoke:
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
ctx.invoked_parents.append(ctx.invoked_with) # type: ignore
if trigger and ctx.invoked_subcommand:
ctx.invoked_with = trigger
await ctx.invoked_subcommand.invoke(ctx)
elif not early_invoke:
# undo the trigger parsing
view.index = previous
view.previous = previous
await super().invoke(ctx)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.invoked_subcommand = None
early_invoke = not self.invoke_without_command
if early_invoke:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
view = ctx.view
previous = view.index
view.skip_ws()
trigger = view.get_word()
if trigger:
ctx.subcommand_passed = trigger
ctx.invoked_subcommand = self.all_commands.get(trigger, None)
if early_invoke:
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
ctx.invoked_parents.append(ctx.invoked_with) # type: ignore
if trigger and ctx.invoked_subcommand:
ctx.invoked_with = trigger
await ctx.invoked_subcommand.reinvoke(ctx, call_hooks=call_hooks)
elif not early_invoke:
# undo the trigger parsing
view.index = previous
view.previous = previous
await super().reinvoke(ctx, call_hooks=call_hooks)
def command(
name: str = ...,
cls: Type[Command[CogT, P, T]] = Command,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]
],
Command[CogT, P, T],
]:
...
def command(
name: str = ...,
cls: Type[CommandT] = Command,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[Cog, ContextT, P], Coro[Any]],
Callable[Concatenate[ContextT, P], Coro[Any]],
]
],
CommandT,
]:
...
def command(
name: str = MISSING,
cls: Union[Type[CommandT], Type[Command[CogT, P, T]]] = MISSING,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[Any]],
Callable[Concatenate[ContextT, P], Coro[Any]],
]
],
Union[Command[CogT, P, T], CommandT],
]:
"""A decorator that transforms a function into a :class:`.Command`
or if called with :func:`.group`, :class:`.Group`.
By default the ``help`` attribute is received automatically from the
docstring of the function and is cleaned up with the use of
``inspect.cleandoc``. If the docstring is ``bytes``, then it is decoded
into :class:`str` using utf-8 encoding.
All checks added using the :func:`.check` & co. decorators are added into
the function. There is no way to supply your own checks through this
decorator.
Parameters
----------
name: :class:`str`
The name to create the command with. By default this uses the
function name unchanged.
cls
The class to construct with. By default this is :class:`.Command`.
You usually do not change this.
attrs
Keyword arguments to pass into the construction of the class denoted
by ``cls``.
Raises
------
TypeError
If the function is not a coroutine or is already a command.
"""
if cls is MISSING:
cls = Command
# Type variables do not seem to nest within decorators.
def decorator(func: Any) -> Union[Command[CogT, P, T], CommandT]:
if isinstance(func, Command):
raise TypeError("Callback is already a command.")
return cls(func, name=name, **attrs)
return decorator
Coro = Coroutine[Any, Any, T]
The provided code snippet includes necessary dependencies for implementing the `group` function. Write a Python function `def group( name: str = MISSING, cls: Union[Type[GroupT], Type[Group[CogT, P, T]]] = MISSING, **attrs: Any, ) -> Callable[ [ Union[ Callable[Concatenate[CogT, ContextT, P], Coro[Any]], Callable[Concatenate[ContextT, P], Coro[Any]], ] ], Union[Group[CogT, P, T], GroupT], ]` to solve the following problem:
A decorator that transforms a function into a :class:`.Group`. This is similar to the :func:`.command` decorator but the ``cls`` parameter is set to :class:`Group` by default. .. versionchanged:: 1.1 The ``cls`` parameter can now be passed.
Here is the function:
def group(
name: str = MISSING,
cls: Union[Type[GroupT], Type[Group[CogT, P, T]]] = MISSING,
**attrs: Any,
) -> Callable[
[
Union[
Callable[Concatenate[CogT, ContextT, P], Coro[Any]],
Callable[Concatenate[ContextT, P], Coro[Any]],
]
],
Union[Group[CogT, P, T], GroupT],
]:
"""A decorator that transforms a function into a :class:`.Group`.
This is similar to the :func:`.command` decorator but the ``cls``
parameter is set to :class:`Group` by default.
.. versionchanged:: 1.1
The ``cls`` parameter can now be passed.
"""
if cls is MISSING:
cls = Group
return command(name=name, cls=cls, **attrs) # type: ignore | A decorator that transforms a function into a :class:`.Group`. This is similar to the :func:`.command` decorator but the ``cls`` parameter is set to :class:`Group` by default. .. versionchanged:: 1.1 The ``cls`` parameter can now be passed. |
160,891 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
class CheckFailure(CommandError):
"""Exception raised when the predicates in :attr:`.Command.checks` have failed.
This inherits from :exc:`CommandError`
"""
class CheckAnyFailure(CheckFailure):
"""Exception raised when all predicates in :func:`check_any` fail.
This inherits from :exc:`CheckFailure`.
.. versionadded:: 1.3
Attributes
----------
errors: List[:class:`CheckFailure`]
A list of errors that were caught during execution.
checks: List[Callable[[:class:`Context`], :class:`bool`]]
A list of check predicates that failed.
"""
def __init__(self, checks: List[CheckFailure], errors: List[Callable[[Context], bool]]) -> None:
self.checks: List[CheckFailure] = checks
self.errors: List[Callable[[Context], bool]] = errors
super().__init__("You do not have permission to run this command.")
Check = Union[
Callable[["Cog", "Context[Any]"], MaybeCoro[bool]], Callable[["Context[Any]"], MaybeCoro[bool]]
]
The provided code snippet includes necessary dependencies for implementing the `check_any` function. Write a Python function `def check_any(*checks: Check) -> Callable[[T], T]` to solve the following problem:
r"""A :func:`check` that is added that checks if any of the checks passed will pass, i.e. using logical OR. If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.CheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. .. versionadded:: 1.3 Parameters ---------- \*checks: Callable[[:class:`Context`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------ TypeError A check passed has not been decorated with the :func:`check` decorator. Examples -------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(ctx): return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!')
Here is the function:
def check_any(*checks: Check) -> Callable[[T], T]:
r"""A :func:`check` that is added that checks if any of the checks passed
will pass, i.e. using logical OR.
If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure.
It inherits from :exc:`.CheckFailure`.
.. note::
The ``predicate`` attribute for this function **is** a coroutine.
.. versionadded:: 1.3
Parameters
----------
\*checks: Callable[[:class:`Context`], :class:`bool`]
An argument list of checks that have been decorated with
the :func:`check` decorator.
Raises
------
TypeError
A check passed has not been decorated with the :func:`check`
decorator.
Examples
--------
Creating a basic check to see if it's the bot owner or
the server owner:
.. code-block:: python3
def is_guild_owner():
def predicate(ctx):
return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id
return commands.check(predicate)
@bot.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
async def only_for_owners(ctx):
await ctx.send('Hello mister owner!')
"""
unwrapped = []
for wrapped in checks:
try:
pred = wrapped.predicate
except AttributeError:
raise TypeError(f"{wrapped!r} must be wrapped by commands.check decorator") from None
else:
unwrapped.append(pred)
async def predicate(ctx: Context) -> bool:
errors = []
for func in unwrapped:
try:
value = await func(ctx)
except CheckFailure as e:
errors.append(e)
else:
if value:
return True
# if we're here, all checks failed
raise CheckAnyFailure(unwrapped, errors)
return check(predicate) | r"""A :func:`check` that is added that checks if any of the checks passed will pass, i.e. using logical OR. If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.CheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. .. versionadded:: 1.3 Parameters ---------- \*checks: Callable[[:class:`Context`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------ TypeError A check passed has not been decorated with the :func:`check` decorator. Examples -------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(ctx): return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_guild_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!') |
160,892 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
from nextcord.errors import ClientException, DiscordException
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class MissingRole(CheckFailure):
"""Exception raised when the command invoker lacks a role to run a command.
This inherits from :exc:`CheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_role: Union[:class:`str`, :class:`int`]
The required role that is missing.
This is the parameter passed to :func:`~.commands.has_role`.
"""
def __init__(self, missing_role: Union[str, int]) -> None:
self.missing_role: Union[str, int] = missing_role
message = f"Role {missing_role!r} is required to run this command."
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `has_role` function. Write a Python function `def has_role(item: Union[int, str]) -> Callable[[T], T]` to solve the following problem:
A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ---------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check.
Here is the function:
def has_role(item: Union[int, str]) -> Callable[[T], T]:
"""A :func:`.check` that is added that checks if the member invoking the
command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including
caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will
return ``False``.
This check raises one of two special exceptions, :exc:`.MissingRole` if the user
is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure`.
.. versionchanged:: 1.1
Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage`
instead of generic :exc:`.CheckFailure`
Parameters
----------
item: Union[:class:`int`, :class:`str`]
The name or ID of the role to check.
"""
def predicate(ctx: Context) -> bool:
if ctx.guild is None:
raise NoPrivateMessage
# ctx.guild is None doesn't narrow ctx.author to Member
if isinstance(item, int):
role = nextcord.utils.get(ctx.author.roles, id=item) # type: ignore
else:
role = nextcord.utils.get(ctx.author.roles, name=item) # type: ignore
if role is None:
raise MissingRole(item)
return True
return check(predicate) | A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ---------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. |
160,893 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
from nextcord.errors import ClientException, DiscordException
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class MissingAnyRole(CheckFailure):
"""Exception raised when the command invoker lacks any of
the roles specified to run a command.
This inherits from :exc:`CheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_roles: List[Union[:class:`str`, :class:`int`]]
The roles that the invoker is missing.
These are the parameters passed to :func:`~.commands.has_any_role`.
"""
def __init__(self, missing_roles: List[Union[str, int]]) -> None:
self.missing_roles: List[Union[str, int]] = missing_roles
missing = [f"'{role}'" for role in missing_roles]
if len(missing) > 2:
fmt = "{}, or {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " or ".join(missing)
message = f"You are missing at least one of the required roles: {fmt}"
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `has_any_role` function. Write a Python function `def has_any_role(*items: Union[int, str]) -> Callable[[T], T]` to solve the following problem:
r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return ``True``. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ---------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example ------- .. code-block:: python3 @bot.command() @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(ctx): await ctx.send('You are cool indeed')
Here is the function:
def has_any_role(*items: Union[int, str]) -> Callable[[T], T]:
r"""A :func:`.check` that is added that checks if the member invoking the
command has **any** of the roles specified. This means that if they have
one out of the three roles specified, then this check will return ``True``.
Similar to :func:`.has_role`\, the names or IDs passed in must be exact.
This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure`.
.. versionchanged:: 1.1
Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage`
instead of generic :exc:`.CheckFailure`
Parameters
----------
items: List[Union[:class:`str`, :class:`int`]]
An argument list of names or IDs to check that the member has roles wise.
Example
-------
.. code-block:: python3
@bot.command()
@commands.has_any_role('Library Devs', 'Moderators', 492212595072434186)
async def cool(ctx):
await ctx.send('You are cool indeed')
"""
def predicate(ctx) -> bool:
if ctx.guild is None:
raise NoPrivateMessage
# ctx.guild is None doesn't narrow ctx.author to Member
getter = functools.partial(nextcord.utils.get, ctx.author.roles)
if any(
getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None
for item in items
):
return True
raise MissingAnyRole(list(items))
return check(predicate) | r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return ``True``. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` Parameters ---------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example ------- .. code-block:: python3 @bot.command() @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) async def cool(ctx): await ctx.send('You are cool indeed') |
160,894 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
from nextcord.errors import ClientException, DiscordException
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class BotMissingRole(CheckFailure):
"""Exception raised when the bot's member lacks a role to run a command.
This inherits from :exc:`CheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_role: Union[:class:`str`, :class:`int`]
The required role that is missing.
This is the parameter passed to :func:`~.commands.has_role`.
"""
def __init__(self, missing_role: Union[str, int]) -> None:
self.missing_role: Union[str, int] = missing_role
message = f"Bot requires the role {missing_role!r} to run this command"
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `bot_has_role` function. Write a Python function `def bot_has_role(item: int) -> Callable[[T], T]` to solve the following problem:
Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure`
Here is the function:
def bot_has_role(item: int) -> Callable[[T], T]:
"""Similar to :func:`.has_role` except checks if the bot itself has the
role.
This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot
is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure`.
.. versionchanged:: 1.1
Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage`
instead of generic :exc:`.CheckFailure`
"""
def predicate(ctx) -> bool:
if ctx.guild is None:
raise NoPrivateMessage
me = ctx.me
if isinstance(item, int):
role = nextcord.utils.get(me.roles, id=item)
else:
role = nextcord.utils.get(me.roles, name=item)
if role is None:
raise BotMissingRole(item)
return True
return check(predicate) | Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` instead of generic :exc:`.CheckFailure` |
160,895 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
from nextcord.errors import ClientException, DiscordException
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class BotMissingAnyRole(CheckFailure):
"""Exception raised when the bot's member lacks any of
the roles specified to run a command.
This inherits from :exc:`CheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_roles: List[Union[:class:`str`, :class:`int`]]
The roles that the bot's member is missing.
These are the parameters passed to :func:`~.commands.has_any_role`.
"""
def __init__(self, missing_roles: List[Union[str, int]]) -> None:
self.missing_roles: List[Union[str, int]] = missing_roles
missing = [f"'{role}'" for role in missing_roles]
if len(missing) > 2:
fmt = "{}, or {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " or ".join(missing)
message = f"Bot is missing at least one of the required roles: {fmt}"
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `bot_has_any_role` function. Write a Python function `def bot_has_any_role(*items: int) -> Callable[[T], T]` to solve the following problem:
Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure
Here is the function:
def bot_has_any_role(*items: int) -> Callable[[T], T]:
"""Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure`.
.. versionchanged:: 1.1
Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage`
instead of generic checkfailure
"""
def predicate(ctx) -> bool:
if ctx.guild is None:
raise NoPrivateMessage
me = ctx.me
getter = functools.partial(nextcord.utils.get, me.roles)
if any(
getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None
for item in items
):
return True
raise BotMissingAnyRole(list(items))
return check(predicate) | Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` instead of generic checkfailure |
160,896 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def _permission_check_wrapper(
predicate: Check, name: str, perms: Dict[str, bool]
) -> Callable[[T], T]:
def wrapper(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
callback = func.callback if isinstance(func, Command) else func
setattr(callback, name, perms)
return check(predicate)(func)
return wrapper # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
from nextcord.errors import ClientException, DiscordException
class MissingPermissions(CheckFailure):
"""Exception raised when the command invoker lacks permissions to run a
command.
This inherits from :exc:`CheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"You are missing {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `has_permissions` function. Write a Python function `def has_permissions(**perms: bool) -> Callable[[T], T]` to solve the following problem:
A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.nextcord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.CheckFailure`. Parameters ---------- perms An argument list of permissions to check for. Example ------- .. code-block:: python3 @bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.')
Here is the function:
def has_permissions(**perms: bool) -> Callable[[T], T]:
"""A :func:`.check` that is added that checks if the member has all of
the permissions necessary.
Note that this check operates on the current channel permissions, not the
guild wide permissions.
The permissions passed in must be exactly like the properties shown under
:class:`.nextcord.Permissions`.
This check raises a special exception, :exc:`.MissingPermissions`
that is inherited from :exc:`.CheckFailure`.
Parameters
----------
perms
An argument list of permissions to check for.
Example
-------
.. code-block:: python3
@bot.command()
@commands.has_permissions(manage_messages=True)
async def test(ctx):
await ctx.send('You can manage messages.')
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(ctx: Context) -> bool:
ch = ctx.channel
permissions = ch.permissions_for(ctx.author) # type: ignore
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise MissingPermissions(missing)
return _permission_check_wrapper(predicate, "__required_permissions", perms) | A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.nextcord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.CheckFailure`. Parameters ---------- perms An argument list of permissions to check for. Example ------- .. code-block:: python3 @bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.') |
160,897 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def _permission_check_wrapper(
predicate: Check, name: str, perms: Dict[str, bool]
) -> Callable[[T], T]:
def wrapper(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
callback = func.callback if isinstance(func, Command) else func
setattr(callback, name, perms)
return check(predicate)(func)
return wrapper # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
from nextcord.errors import ClientException, DiscordException
class BotMissingPermissions(CheckFailure):
"""Exception raised when the bot's member lacks permissions to run a
command.
This inherits from :exc:`CheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"Bot requires {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `bot_has_permissions` function. Write a Python function `def bot_has_permissions(**perms: bool) -> Callable[[T], T]` to solve the following problem:
Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.BotMissingPermissions` that is inherited from :exc:`.CheckFailure`.
Here is the function:
def bot_has_permissions(**perms: bool) -> Callable[[T], T]:
"""Similar to :func:`.has_permissions` except checks if the bot itself has
the permissions listed.
This check raises a special exception, :exc:`.BotMissingPermissions`
that is inherited from :exc:`.CheckFailure`.
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(ctx: Context) -> bool:
guild = ctx.guild
me = guild.me if guild is not None else ctx.bot.user
permissions = ctx.channel.permissions_for(me) # type: ignore
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise BotMissingPermissions(missing)
return _permission_check_wrapper(predicate, "__required_bot_permissions", perms) | Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.BotMissingPermissions` that is inherited from :exc:`.CheckFailure`. |
160,898 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def _permission_check_wrapper(
predicate: Check, name: str, perms: Dict[str, bool]
) -> Callable[[T], T]:
def wrapper(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
callback = func.callback if isinstance(func, Command) else func
setattr(callback, name, perms)
return check(predicate)(func)
return wrapper # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
from nextcord.errors import ClientException, DiscordException
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class MissingPermissions(CheckFailure):
"""Exception raised when the command invoker lacks permissions to run a
command.
This inherits from :exc:`CheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"You are missing {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `has_guild_permissions` function. Write a Python function `def has_guild_permissions(**perms: bool) -> Callable[[T], T]` to solve the following problem:
Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.NoPrivateMessage`. .. versionadded:: 1.3
Here is the function:
def has_guild_permissions(**perms: bool) -> Callable[[T], T]:
"""Similar to :func:`.has_permissions`, but operates on guild wide
permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an
exception, :exc:`.NoPrivateMessage`.
.. versionadded:: 1.3
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(ctx: Context) -> bool:
if not ctx.guild:
raise NoPrivateMessage
permissions = ctx.author.guild_permissions # type: ignore
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise MissingPermissions(missing)
return _permission_check_wrapper(predicate, "__required_guild_permissions", perms) | Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.NoPrivateMessage`. .. versionadded:: 1.3 |
160,899 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def _permission_check_wrapper(
predicate: Check, name: str, perms: Dict[str, bool]
) -> Callable[[T], T]:
def wrapper(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
callback = func.callback if isinstance(func, Command) else func
setattr(callback, name, perms)
return check(predicate)(func)
return wrapper # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
from nextcord.errors import ClientException, DiscordException
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class BotMissingPermissions(CheckFailure):
"""Exception raised when the bot's member lacks permissions to run a
command.
This inherits from :exc:`CheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"Bot requires {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `bot_has_guild_permissions` function. Write a Python function `def bot_has_guild_permissions(**perms: bool) -> Callable[[T], T]` to solve the following problem:
Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions. .. versionadded:: 1.3
Here is the function:
def bot_has_guild_permissions(**perms: bool) -> Callable[[T], T]:
"""Similar to :func:`.has_guild_permissions`, but checks the bot
members guild permissions.
.. versionadded:: 1.3
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(ctx: Context) -> bool:
if not ctx.guild:
raise NoPrivateMessage
permissions = ctx.me.guild_permissions # type: ignore
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise BotMissingPermissions(missing)
return _permission_check_wrapper(predicate, "__required_bot_guild_permissions", perms) | Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions. .. versionadded:: 1.3 |
160,900 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
class PrivateMessageOnly(CheckFailure):
"""Exception raised when an operation does not work outside of private
message contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command can only be used in private messages.")
The provided code snippet includes necessary dependencies for implementing the `dm_only` function. Write a Python function `def dm_only() -> Callable[[T], T]` to solve the following problem:
A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.PrivateMessageOnly` that is inherited from :exc:`.CheckFailure`. .. versionadded:: 1.1
Here is the function:
def dm_only() -> Callable[[T], T]:
"""A :func:`.check` that indicates this command must only be used in a
DM context. Only private messages are allowed when
using the command.
This check raises a special exception, :exc:`.PrivateMessageOnly`
that is inherited from :exc:`.CheckFailure`.
.. versionadded:: 1.1
"""
def predicate(ctx: Context) -> bool:
if ctx.guild is not None:
raise PrivateMessageOnly
return True
return check(predicate) | A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.PrivateMessageOnly` that is inherited from :exc:`.CheckFailure`. .. versionadded:: 1.1 |
160,901 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
class NoPrivateMessage(CheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`CheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
The provided code snippet includes necessary dependencies for implementing the `guild_only` function. Write a Python function `def guild_only() -> Callable[[T], T]` to solve the following problem:
A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited from :exc:`.CheckFailure`.
Here is the function:
def guild_only() -> Callable[[T], T]:
"""A :func:`.check` that indicates this command must only be used in a
guild context only. Basically, no private messages are allowed when
using the command.
This check raises a special exception, :exc:`.NoPrivateMessage`
that is inherited from :exc:`.CheckFailure`.
"""
def predicate(ctx: Context) -> bool:
if ctx.guild is None:
raise NoPrivateMessage
return True
return check(predicate) | A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited from :exc:`.CheckFailure`. |
160,902 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
class NotOwner(CheckFailure):
"""Exception raised when the message author is not the owner of the bot.
This inherits from :exc:`CheckFailure`
"""
The provided code snippet includes necessary dependencies for implementing the `is_owner` function. Write a Python function `def is_owner() -> Callable[[T], T]` to solve the following problem:
A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`.
Here is the function:
def is_owner() -> Callable[[T], T]:
"""A :func:`.check` that checks if the person invoking this command is the
owner of the bot.
This is powered by :meth:`.Bot.is_owner`.
This check raises a special exception, :exc:`.NotOwner` that is derived
from :exc:`.CheckFailure`.
"""
async def predicate(ctx: Context) -> bool:
if not await ctx.bot.is_owner(ctx.author):
raise NotOwner("You do not own this bot.")
return True
return check(predicate) | A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. |
160,903 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
def check(predicate: Check) -> Callable[[T], T]:
r"""A decorator that adds a check to the :class:`.Command` or its
subclasses. These checks could be accessed via :attr:`.Command.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Context`. If the check returns a ``False``\-like value then
during invocation a :exc:`.CheckFailure` exception is raised and sent to
the :func:`.on_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.CommandError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`.on_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return ctx.guild.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
.. versionchanged:: 1.3
The ``predicate`` attribute was added.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(ctx):
return ctx.message.author.id == 85309593344815104
async def only_for_me(ctx):
await ctx.send('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
async def only_me(ctx):
await ctx.send('Only you!')
Parameters
----------
predicate: Callable[[:class:`Context`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.checks.append(predicate)
else:
if not hasattr(func, "__commands_checks__"):
func.__commands_checks__ = []
func.__commands_checks__.append(predicate)
return func
if asyncio.iscoroutinefunction(predicate):
decorator.predicate = predicate
else:
async def wrapper(ctx):
return predicate(ctx) # type: ignore
decorator.predicate = wrapper
return decorator # type: ignore
class Context(nextcord.abc.Messageable, Generic[BotT]):
r"""Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the :class:`~nextcord.abc.Messageable` ABC.
Attributes
----------
message: :class:`.Message`
The message that triggered the command being executed.
bot: :class:`.Bot`
The bot that contains the command being executed.
args: :class:`list`
The list of transformed arguments that were passed into the command.
If this is accessed during the :func:`.on_command_error` event
then this list could be incomplete.
kwargs: :class:`dict`
A dictionary of transformed arguments that were passed into the command.
Similar to :attr:`args`\, if this is accessed in the
:func:`.on_command_error` event then this dict could be incomplete.
current_parameter: Optional[:class:`inspect.Parameter`]
The parameter that is currently being inspected and converted.
This is only of use for within converters.
.. versionadded:: 2.0
prefix: Optional[:class:`str`]
The prefix that was used to invoke the command.
command: Optional[:class:`Command`]
The command that is being invoked currently.
invoked_with: Optional[:class:`str`]
The command name that triggered this invocation. Useful for finding out
which alias called the command.
invoked_parents: List[:class:`str`]
The command names of the parents that triggered this invocation. Useful for
finding out which aliases called the command.
For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``.
.. versionadded:: 1.7
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked.
If no valid subcommand was invoked then this is equal to ``None``.
subcommand_passed: Optional[:class:`str`]
The string that was attempted to call a subcommand. This does not have
to point to a valid registered subcommand and could just point to a
nonsense string. If nothing was passed to attempt a call to a
subcommand then this is set to ``None``.
command_failed: :class:`bool`
A boolean that indicates if the command failed to be parsed, checked,
or invoked.
"""
def __init__(
self,
*,
message: Message,
bot: BotT,
view: StringView,
args: List[Any] = MISSING,
kwargs: Dict[str, Any] = MISSING,
prefix: Optional[str] = None,
command: Optional[Command] = None,
invoked_with: Optional[str] = None,
invoked_parents: List[str] = MISSING,
invoked_subcommand: Optional[Command] = None,
subcommand_passed: Optional[str] = None,
command_failed: bool = False,
current_parameter: Optional[inspect.Parameter] = None,
) -> None:
self.message: Message = message
self.bot: BotT = bot
self.args: List[Any] = args or []
self.kwargs: Dict[str, Any] = kwargs or {}
self.prefix: Optional[str] = prefix
self.command: Optional[Command] = command
self.view: StringView = view
self.invoked_with: Optional[str] = invoked_with
self.invoked_parents: List[str] = invoked_parents or []
self.invoked_subcommand: Optional[Command] = invoked_subcommand
self.subcommand_passed: Optional[str] = subcommand_passed
self.command_failed: bool = command_failed
self.current_parameter: Optional[inspect.Parameter] = current_parameter
self._state: ConnectionState = self.message._state
async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
----------
command: :class:`.Command`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None:
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derived exceptions,
it is recommended to use the regular :meth:`~.Context.invoke`
as it will work more naturally. After all, this will end up
using the old arguments the user has used and will thus just
fail again.
Parameters
----------
call_hooks: :class:`bool`
Whether to call the before and after invoke hooks.
restart: :class:`bool`
Whether to start the call chain from the very beginning
or where we left off (i.e. the command that caused the error).
The default is to start where we left off.
Raises
------
ValueError
The context to reinvoke is not valid.
"""
cmd = self.command
view = self.view
if cmd is None:
raise ValueError("This context is not valid.")
# some state to revert to when we're done
index, previous = view.index, view.previous
invoked_with = self.invoked_with
invoked_subcommand = self.invoked_subcommand
invoked_parents = self.invoked_parents
subcommand_passed = self.subcommand_passed
if restart:
to_call = cmd.root_parent or cmd
view.index = len(self.prefix or "")
view.previous = 0
self.invoked_parents = []
self.invoked_with = view.get_word() # advance to get the root command
else:
to_call = cmd
try:
await to_call.reinvoke(self, call_hooks=call_hooks)
finally:
self.command = cmd
view.index = index
view.previous = previous
self.invoked_with = invoked_with
self.invoked_subcommand = invoked_subcommand
self.invoked_parents = invoked_parents
self.subcommand_passed = subcommand_passed
def valid(self) -> bool:
""":class:`bool`: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None
async def _get_channel(self) -> nextcord.abc.Messageable:
return self.channel
def clean_prefix(self) -> str:
""":class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
.. versionadded:: 2.0
"""
if self.prefix is None:
return ""
user = self.me
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the
# odd one.
pattern = re.compile(r"<@!?%s>" % user.id)
return pattern.sub("@%s" % user.display_name.replace("\\", r"\\"), self.prefix)
def cog(self) -> Optional[Cog]:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist."""
if self.command is None:
return None
return self.command.cog
def guild(self) -> Optional[Guild]:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
return self.message.guild
def channel(self) -> MessageableChannel:
"""Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command.
Shorthand for :attr:`.Message.channel`.
"""
return self.message.channel
def author(self) -> Union[User, Member]:
"""Union[:class:`~nextcord.User`, :class:`.Member`]:
Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`
"""
return self.message.author
def me(self) -> Union[Member, ClientUser]:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts.
"""
# bot.user will never be None at this point.
return self.guild.me if self.guild is not None else self.bot.user # type: ignore
def voice_client(self) -> Optional[VoiceProtocol]:
r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable."""
g = self.guild
return g.voice_client if g else None
async def send_help(self, *args: Any) -> Any:
"""send_help(entity=<bot>)
|coro|
Shows the help command for the specified entity if given.
The entity can be a command or a cog.
If no entity is given, then it'll show help for the
entire bot.
If the entity is a string, then it looks up whether it's a
:class:`Cog` or a :class:`Command`.
.. note::
Due to the way this function works, instead of returning
something similar to :meth:`~.commands.HelpCommand.command_not_found`
this returns :class:`None` on bad input or no help command.
Parameters
----------
entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]]
The entity to show help for.
Returns
-------
Any
The result of the help command, if any.
"""
from .core import Command, Group, wrap_callback
from .errors import CommandError
bot = self.bot
cmd = bot.help_command
if cmd is None:
return None
cmd = cmd.copy()
cmd.context = self
if len(args) == 0:
await cmd.prepare_help_command(self, None)
mapping = cmd.get_bot_mapping()
injected = wrap_callback(cmd.send_bot_help)
try:
return await injected(mapping)
except CommandError as e:
await cmd.on_help_command_error(self, e)
return None
entity = args[0]
if isinstance(entity, str):
entity = bot.get_cog(entity) or bot.get_command(entity)
if entity is None:
return None
if not hasattr(entity, "qualified_name"):
# if we're here then it's not a cog, group, or command.
return None
await cmd.prepare_help_command(self, entity.qualified_name)
try:
if hasattr(entity, "__cog_commands__"):
injected = wrap_callback(cmd.send_cog_help)
return await injected(entity)
if isinstance(entity, Group):
injected = wrap_callback(cmd.send_group_help)
return await injected(entity)
if isinstance(entity, Command):
injected = wrap_callback(cmd.send_command_help)
return await injected(entity)
return None
except CommandError as e:
await cmd.on_help_command_error(self, e)
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
return await self.message.reply(content, **kwargs)
from nextcord.errors import ClientException, DiscordException
class NSFWChannelRequired(CheckFailure):
"""Exception raised when a channel does not have the required NSFW setting.
This inherits from :exc:`CheckFailure`.
.. versionadded:: 1.1
Parameters
----------
channel: Union[:class:`.abc.GuildChannel`, :class:`.Thread`]
The channel that does not have NSFW enabled.
"""
def __init__(self, channel: Union[GuildChannel, Thread]) -> None:
self.channel: Union[GuildChannel, Thread] = channel
super().__init__(f"Channel '{channel}' needs to be NSFW for this command to work.")
The provided code snippet includes necessary dependencies for implementing the `is_nsfw` function. Write a Python function `def is_nsfw() -> Callable[[T], T]` to solve the following problem:
A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check.
Here is the function:
def is_nsfw() -> Callable[[T], T]:
"""A :func:`.check` that checks if the channel is a NSFW channel.
This check raises a special exception, :exc:`.NSFWChannelRequired`
that is derived from :exc:`.CheckFailure`.
.. versionchanged:: 1.1
Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`.
DM channels will also now pass this check.
"""
def pred(ctx: Context) -> bool:
ch = ctx.channel
if ctx.guild is None or (
isinstance(ch, (nextcord.TextChannel, nextcord.Thread)) and ch.is_nsfw()
):
return True
raise NSFWChannelRequired(ch) # type: ignore
return check(pred) | A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1 Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`. DM channels will also now pass this check. |
160,904 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
class Command(_BaseCommand, Generic[CogT, P, T]):
r"""A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The coroutine that is executed when the command is called.
help: Optional[:class:`str`]
The long help text for the command.
brief: Optional[:class:`str`]
The short help text for the command.
usage: Optional[:class:`str`]
A replacement for arguments in the default help text.
aliases: Union[List[:class:`str`], Tuple[:class:`str`]]
The list of aliases the command can be invoked under.
enabled: :class:`bool`
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
:exc:`.DisabledCommand` is raised to the :func:`.on_command_error`
event. Defaults to ``True``.
parent: Optional[:class:`Group`]
The parent group that this command belongs to. ``None`` if there
isn't one.
cog: Optional[:class:`Cog`]
The cog that this command belongs to. ``None`` if there isn't one.
checks: List[Callable[[:class:`.Context`], :class:`bool`]]
A list of predicates that verifies if the command could be executed
with the given :class:`.Context` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.CommandError` should be used. Note that if the checks fail then
:exc:`.CheckFailure` exception is raised to the :func:`.on_command_error`
event.
description: :class:`str`
The message prefixed into the default help command.
hidden: :class:`bool`
If ``True``\, the default help command does not show this in the
help output.
rest_is_raw: :class:`bool`
If ``False`` and a keyword-only argument is provided then the keyword
only argument is stripped and handled as if it was a regular argument
that handles :exc:`.MissingRequiredArgument` and default values in a
regular matter rather than passing the rest completely raw. If ``True``
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults to ``False``.
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked, if any.
require_var_positional: :class:`bool`
If ``True`` and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults to ``False``.
.. versionadded:: 1.5
ignore_extra: :class:`bool`
If ``True``\, ignores extraneous strings passed to a command if all its
requirements are met (e.g. ``?foo a b c`` when only expecting ``a``
and ``b``). Otherwise :func:`.on_command_error` and local error handlers
are called with :exc:`.TooManyArguments`. Defaults to ``True``.
cooldown_after_parsing: :class:`bool`
If ``True``\, cooldown processing is done after argument parsing,
which calls converters. If ``False`` then cooldown processing is done
first and then the converters are called second. Defaults to ``False``.
extras: :class:`dict`
A dict of user provided extras to attach to the Command.
.. note::
This object may be copied by the library.
.. versionadded:: 2.0
inherit_hooks: :class:`bool`
If ``True`` and this command has a parent :class:`Group` then this command
will inherit all checks, pre_invoke and after_invoke's defined on the the :class:`Group`
This defaults to ``False``
.. note::
Any ``pre_invoke`` or ``after_invoke``'s defined on this will override parent ones.
.. versionadded:: 2.0.0
"""
__original_kwargs__: Dict[str, Any]
def __new__(cls, *_args: Any, **kwargs: Any) -> Self:
# if you're wondering why this is done, it's because we need to ensure
# we have a complete original copy of **kwargs even for classes that
# mess with it by popping before delegating to the subclass __init__.
# In order to do this, we need to control the instance creation and
# inject the original kwargs through __new__ rather than doing it
# inside __init__.
self = super().__new__(cls)
# we do a shallow copy because it's probably the most common use case.
# this could potentially break if someone modifies a list or something
# while it's in movement, but for now this is the cheapest and
# fastest way to do what we want.
self.__original_kwargs__ = kwargs.copy()
return self
def __init__(
self,
func: Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
],
**kwargs: Any,
) -> None:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine.")
name = kwargs.get("name") or func.__name__
if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
self.name: str = name
# ContextT is incompatible with normal Context
self.callback = func # pyright: ignore
self.enabled: bool = kwargs.get("enabled", True)
help_doc = kwargs.get("help")
if help_doc is not None:
help_doc = inspect.cleandoc(help_doc)
else:
help_doc = inspect.getdoc(func)
if isinstance(help_doc, bytes):
help_doc = help_doc.decode("utf-8")
self.help: Optional[str] = help_doc
self.brief: Optional[str] = kwargs.get("brief")
self.usage: Optional[str] = kwargs.get("usage")
self.rest_is_raw: bool = kwargs.get("rest_is_raw", False)
self.aliases: Union[List[str], Tuple[str]] = kwargs.get("aliases", [])
self.extras: Dict[str, Any] = kwargs.get("extras", {})
if not isinstance(self.aliases, (list, tuple)):
raise TypeError("Aliases of a command must be a list or a tuple of strings.")
self.description: str = inspect.cleandoc(kwargs.get("description", ""))
self.hidden: bool = kwargs.get("hidden", False)
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks: List[Check] = checks
try:
cooldown = func.__commands_cooldown__
except AttributeError:
cooldown = kwargs.get("cooldown")
if cooldown is None:
buckets = CooldownMapping(cooldown, BucketType.default)
elif isinstance(cooldown, CooldownMapping):
buckets = cooldown
else:
raise TypeError("Cooldown must be an instance of CooldownMapping or None.")
self._buckets: CooldownMapping = buckets
try:
max_concurrency = func.__commands_max_concurrency__
except AttributeError:
max_concurrency = kwargs.get("max_concurrency")
self._max_concurrency: Optional[MaxConcurrency] = max_concurrency
self.require_var_positional: bool = kwargs.get("require_var_positional", False)
self.ignore_extra: bool = kwargs.get("ignore_extra", True)
self.cooldown_after_parsing: bool = kwargs.get("cooldown_after_parsing", False)
self.cog: Optional[CogT] = None
# bandaid for the fact that sometimes parent can be the bot instance
parent = kwargs.get("parent")
self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore
self._before_invoke: Optional[Hook] = None
try:
before_invoke = func.__before_invoke__
except AttributeError:
pass
else:
self.before_invoke(before_invoke)
self._after_invoke: Optional[Hook] = None
try:
after_invoke = func.__after_invoke__
except AttributeError:
pass
else:
self.after_invoke(after_invoke)
# Attempt to bind to parent hooks if applicable
if not kwargs.get("inherit_hooks", False):
return
# We should be binding hooks
if not self.parent:
return
inherited_before_invoke: Optional[Hook] = None
try:
inherited_before_invoke = self.parent._before_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_before_invoke:
self.before_invoke(inherited_before_invoke)
inherited_after_invoke: Optional[Hook] = None
try:
inherited_after_invoke = self.parent._after_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_after_invoke:
self.after_invoke(inherited_after_invoke)
self.checks.extend(self.parent.checks) # type: ignore
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_guild_permissions", {})
def callback(
self,
) -> Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]:
return self._callback
def callback(
self,
function: Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
],
) -> None:
self._callback = function
unwrap = unwrap_function(function)
self.module = unwrap.__module__
try:
globalns = unwrap.__globals__
except AttributeError:
globalns = {}
self.params = get_signature_parameters(function, globalns)
def add_check(self, func: Check) -> None:
"""Adds a check to the command.
This is the non-decorator interface to :func:`.check`.
.. versionadded:: 1.3
Parameters
----------
func
The function that will be used as a check.
"""
self.checks.append(func)
def remove_check(self, func: Check) -> None:
"""Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command's checks.
.. versionadded:: 1.3
Parameters
----------
func
The function to remove from the checks.
"""
with contextlib.suppress(ValueError):
self.checks.remove(func)
def update(self, **kwargs: Any) -> None:
"""Updates :class:`Command` instance with updated attribute.
This works similarly to the :func:`.command` decorator in terms
of parameters in that they are passed to the :class:`Command` or
subclass constructors, sans the name and callback.
"""
self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs))
async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T:
"""|coro|
Calls the internal callback that the command holds.
.. note::
This bypasses all mechanisms -- including checks, converters,
invoke hooks, cooldowns, etc. You must take care to pass
the proper arguments and types to this function.
.. versionadded:: 1.3
"""
if self.cog is not None:
return await self.callback(self.cog, context, *args, **kwargs) # type: ignore
return await self.callback(context, *args, **kwargs) # type: ignore
def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT:
other._before_invoke = self._before_invoke
other._after_invoke = self._after_invoke
if self.checks != other.checks:
other.checks = self.checks.copy()
if self._buckets.valid and not other._buckets.valid:
other._buckets = self._buckets.copy()
if self._max_concurrency != other._max_concurrency:
# _max_concurrency won't be None at this point
other._max_concurrency = self._max_concurrency.copy() # type: ignore
with contextlib.suppress(AttributeError):
other.on_error = self.on_error
return other
def copy(self) -> Self:
"""Creates a copy of this command.
Returns
-------
:class:`Command`
A new instance of this command.
"""
ret = self.__class__(self.callback, **self.__original_kwargs__)
return self._ensure_assignment_on_copy(ret)
def _update_copy(self, kwargs: Dict[str, Any]) -> Self:
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = self.__class__(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
return self.copy()
async def dispatch_error(self, ctx: Context, error: Exception) -> None:
ctx.command_failed = True
cog = self.cog
try:
coro = self.on_error
except AttributeError:
pass
else:
injected = wrap_callback(coro)
if cog is not None:
await injected(cog, ctx, error)
else:
await injected(ctx, error)
try:
if cog is not None:
local = Cog._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch("command_error", ctx, error)
async def transform(self, ctx: Context, param: inspect.Parameter) -> Any:
required = param.default is param.empty
converter = get_converter(param)
consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw
view = ctx.view
view.skip_ws()
# The greedy converter is simple -- it keeps going until it fails in which case,
# it undos the view ready for the next parameter to use instead
if isinstance(converter, Greedy):
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
return await self._transform_greedy_pos(ctx, param, required, converter.converter)
if param.kind == param.VAR_POSITIONAL:
return await self._transform_greedy_var_pos(ctx, param, converter.converter)
# if we're here, then it's a KEYWORD_ONLY param type
# since this is mostly useless, we'll helpfully transform Greedy[X]
# into just X and do the parsing that way.
converter = converter.converter
if view.eof:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError # break the loop
if required:
if self._is_typing_optional(param.annotation):
return None
if hasattr(converter, "__commands_is_flag__") and converter._can_be_constructible():
return await converter._construct_default(ctx)
raise MissingRequiredArgument(param)
return param.default
previous = view.index
if consume_rest_is_special:
argument = view.read_rest().strip()
else:
try:
argument = view.get_quoted_word()
except ArgumentParsingError:
if self._is_typing_optional(param.annotation):
view.index = previous
return None
raise
view.previous = previous
if argument is None:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError
if required:
if self._is_typing_optional(param.annotation):
return None
raise MissingRequiredArgument(param)
return param.default
# type-checker fails to narrow argument
return await run_converters(ctx, converter, argument, param)
async def _transform_greedy_pos(
self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any
) -> Any:
view = ctx.view
result = []
while not view.eof:
# for use with a manual undo
previous = view.index
view.skip_ws()
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
break
else:
result.append(value)
if not result and not required:
return param.default
return result
async def _transform_greedy_var_pos(
self, ctx: Context, param: inspect.Parameter, converter: Any
) -> Any:
view = ctx.view
previous = view.index
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
raise RuntimeError from None # break loop
else:
return value
def clean_params(self) -> Dict[str, inspect.Parameter]:
"""Dict[:class:`str`, :class:`inspect.Parameter`]:
Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'self' parameter") from None
try:
# first/second parameter is context
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'context' parameter") from None
return result
def full_parent_name(self) -> str:
""":class:`str`: Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``.
"""
entries = []
command = self
# command.parent is type-hinted as GroupMixin some attributes are resolved via MRO
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command.name) # type: ignore
return " ".join(reversed(entries))
def parents(self) -> List[Group]:
"""List[:class:`Group`]: Retrieves the parents of this command.
If the command has no parents then it returns an empty :class:`list`.
For example in commands ``?a b c test``, the parents are ``[c, b, a]``.
.. versionadded:: 1.1
"""
entries = []
command = self
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command)
return entries
def root_parent(self) -> Optional[Group]:
"""Optional[:class:`Group`]: Retrieves the root parent of this command.
If the command has no parents then it returns ``None``.
For example in commands ``?a b c test``, the root parent is ``a``.
"""
if not self.parent:
return None
return self.parents[-1]
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return parent + " " + self.name
return self.name
def __str__(self) -> str:
return self.qualified_name
async def _parse_arguments(self, ctx: Context) -> None:
ctx.args = [ctx] if self.cog is None else [self.cog, ctx]
ctx.kwargs = {}
args = ctx.args
kwargs = ctx.kwargs
view = ctx.view
iterator = iter(self.params.items())
if self.cog is not None:
# we have 'self' as the first parameter so just advance
# the iterator and resume parsing
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "self" parameter.'
) from None
# next we have the 'ctx' as the next parameter
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "ctx" parameter.'
) from None
for name, param in iterator:
ctx.current_parameter = param
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
transformed = await self.transform(ctx, param)
args.append(transformed)
elif param.kind == param.KEYWORD_ONLY:
# kwarg only param denotes "consume rest" semantics
if self.rest_is_raw:
converter = get_converter(param)
argument = view.read_rest()
kwargs[name] = await run_converters(ctx, converter, argument, param)
else:
kwargs[name] = await self.transform(ctx, param)
break
elif param.kind == param.VAR_POSITIONAL:
if view.eof and self.require_var_positional:
raise MissingRequiredArgument(param)
while not view.eof:
try:
transformed = await self.transform(ctx, param)
args.append(transformed)
except RuntimeError:
break
if not self.ignore_extra and not view.eof:
raise TooManyArguments("Too many arguments passed to " + self.qualified_name)
async def call_before_hooks(self, ctx: Context) -> None:
# now that we're done preparing we can call the pre-command hooks
# first, call the command local hook:
cog = self.cog
if self._before_invoke is not None:
# should be cog if @commands.before_invoke is used
instance = getattr(self._before_invoke, "__self__", cog)
# __self__ only exists for methods, not functions
# however, if @command.before_invoke is used, it will be a function
if instance:
await self._before_invoke(instance, ctx) # type: ignore
else:
await self._before_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_before_invoke)
if hook is not None:
await hook(ctx)
# call the bot global hook if necessary
hook = ctx.bot._before_invoke
if hook is not None:
await hook(ctx)
async def call_after_hooks(self, ctx: Context) -> None:
cog = self.cog
if self._after_invoke is not None:
instance = getattr(self._after_invoke, "__self__", cog)
if instance:
await self._after_invoke(instance, ctx) # type: ignore
else:
await self._after_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
def _prepare_cooldowns(self, ctx: Context) -> None:
if self._buckets.valid:
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
bucket = self._buckets.get_bucket(ctx.message, current)
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
async def prepare(self, ctx: Context) -> None:
ctx.command = self
if not await self.can_run(ctx):
raise CheckFailure(f"The check functions for command {self.qualified_name} failed.")
if self._max_concurrency is not None:
# For this application, context can be duck-typed as a Message
await self._max_concurrency.acquire(ctx) # type: ignore
try:
if self.cooldown_after_parsing:
await self._parse_arguments(ctx)
self._prepare_cooldowns(ctx)
else:
self._prepare_cooldowns(ctx)
await self._parse_arguments(ctx)
await self.call_before_hooks(ctx)
except:
if self._max_concurrency is not None:
await self._max_concurrency.release(ctx) # type: ignore
raise
def is_on_cooldown(self, ctx: Context) -> bool:
"""Checks whether the command is currently on cooldown.
Parameters
----------
ctx: :class:`.Context`
The invocation context to use when checking the commands cooldown status.
Returns
-------
:class:`bool`
A boolean indicating if the command is on cooldown.
"""
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_tokens(current) == 0
def reset_cooldown(self, ctx: Context) -> None:
"""Resets the cooldown on this command.
Parameters
----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.reset()
def get_cooldown_retry_after(self, ctx: Context) -> float:
"""Retrieves the amount of seconds before this command can be tried again.
.. versionadded:: 1.4
Parameters
----------
ctx: :class:`.Context`
The invocation context to retrieve the cooldown from.
Returns
-------
:class:`float`
The amount of time left on this command's cooldown in seconds.
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_retry_after(current)
return 0.0
async def invoke(self, ctx: Context) -> None:
await self.prepare(ctx)
# terminate the invoked_subcommand chain.
# since we're in a regular command (and not a group) then
# the invoked subcommand is None.
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
ctx.invoked_subcommand = None
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
def error(self, coro: ErrorT) -> ErrorT:
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The error handler must be a coroutine.")
self.on_error: Error = coro
return coro
def has_error_handler(self) -> bool:
""":class:`bool`: Checks whether the command has an error handler registered.
.. versionadded:: 1.7
"""
return hasattr(self, "on_error")
def before_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The pre-invoke hook must be a coroutine.")
self._before_invoke = coro
return coro
def after_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The post-invoke hook must be a coroutine.")
self._after_invoke = coro
return coro
def cog_name(self) -> Optional[str]:
"""Optional[:class:`str`]: The name of the cog this command belongs to, if any."""
return type(self.cog).__cog_name__ if self.cog is not None else None
def short_doc(self) -> str:
""":class:`str`: Gets the "short" documentation of a command.
By default, this is the :attr:`.brief` attribute.
If that lookup leads to an empty string then the first line of the
:attr:`.help` attribute is used instead.
"""
if self.brief is not None:
return self.brief
if self.help is not None:
return self.help.split("\n", 1)[0]
return ""
def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]:
return getattr(annotation, "__origin__", None) is Union and type(None) in annotation.__args__ # type: ignore
def signature(self) -> str:
""":class:`str`: Returns a POSIX-like signature useful for help command output."""
if self.usage is not None:
return self.usage
params = self.clean_params
if not params:
return ""
result = []
for name, param in params.items():
greedy = isinstance(param.annotation, Greedy)
optional = False # postpone evaluation of if it's an optional argument
# for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the
# parameter signature is a literal list of it's values
annotation = param.annotation.converter if greedy else param.annotation
origin = getattr(annotation, "__origin__", None)
if not greedy and origin is Union:
none_cls = type(None)
union_args = annotation.__args__
optional = union_args[-1] is none_cls
if len(union_args) == 2 and optional:
annotation = union_args[0]
origin = getattr(annotation, "__origin__", None)
if origin is Literal:
name = "|".join(
f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__
)
if param.default is not param.empty:
# We don't want None or '' to trigger the [name=value] case and instead it should
# do [name] since [name=None] or [name=] are not exactly useful for the user.
should_print = (
param.default if isinstance(param.default, str) else param.default is not None
)
if should_print:
result.append(
f"[{name}={param.default}]"
if not greedy
else f"[{name}={param.default}]..."
)
continue
result.append(f"[{name}]")
elif param.kind == param.VAR_POSITIONAL:
if self.require_var_positional:
result.append(f"<{name}...>")
else:
result.append(f"[{name}...]")
elif greedy:
result.append(f"[{name}]...")
elif optional:
result.append(f"[{name}]")
else:
result.append(f"<{name}>")
return " ".join(result)
async def can_run(self, ctx: Context) -> bool:
"""|coro|
Checks if the command can be executed by checking all the predicates
inside the :attr:`~Command.checks` attribute. This also checks whether the
command is disabled.
.. versionchanged:: 1.3
Checks whether the command is disabled or not
Parameters
----------
ctx: :class:`.Context`
The ctx of the command currently being invoked.
Raises
------
:class:`CommandError`
Any command error that was raised during a check call will be propagated
by this function.
Returns
-------
:class:`bool`
A boolean indicating if the command can be invoked.
"""
if not self.enabled:
raise DisabledCommand(f"{self.name} command is disabled")
original = ctx.command
ctx.command = self
try:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.qualified_name} failed."
)
cog = self.cog
if cog is not None:
local_check = Cog._get_overridden_method(cog.cog_check)
if local_check is not None:
ret = await nextcord.utils.maybe_coroutine(local_check, ctx)
if not ret:
return False
predicates = self.checks
if not predicates:
# since we have no checks, then we just return True.
return True
return await nextcord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
finally:
ctx.command = original
class BucketType(IntEnum):
default = 0
user = 1
guild = 2
channel = 3
member = 4
category = 5
role = 6
def get_key(self, msg: Message) -> Any:
if self is BucketType.user:
return msg.author.id
if self is BucketType.guild:
return (msg.guild or msg.author).id
if self is BucketType.channel:
return msg.channel.id
if self is BucketType.member:
return ((msg.guild and msg.guild.id), msg.author.id)
if self is BucketType.category:
return (msg.channel.category or msg.channel).id # type: ignore
if self is BucketType.role:
# we return the channel id of a private-channel as there are only roles in guilds
# and that yields the same result as for a guild with only the @everyone role
# NOTE: PrivateChannel doesn't actually have an id attribute but we assume we are
# recieving a DMChannel or GroupChannel which inherit from PrivateChannel and do
return (msg.channel if isinstance(msg.channel, PrivateChannel) else msg.author.top_role).id # type: ignore
return None
def __call__(self, msg: Message) -> Any:
return self.get_key(msg)
class Cooldown:
"""Represents a cooldown for a command.
Attributes
----------
rate: :class:`int`
The total number of tokens available per :attr:`per` seconds.
per: :class:`float`
The length of the cooldown period in seconds.
"""
__slots__ = ("rate", "per", "_window", "_tokens", "_last")
def __init__(self, rate: float, per: float) -> None:
self.rate: int = int(rate)
self.per: float = float(per)
self._window: float = 0.0
self._tokens: int = self.rate
self._last: float = 0.0
def get_tokens(self, current: Optional[float] = None) -> int:
"""Returns the number of available tokens before rate limiting is applied.
Parameters
----------
current: Optional[:class:`float`]
The time in seconds since Unix epoch to calculate tokens at.
If not supplied then :func:`time.time()` is used.
Returns
-------
:class:`int`
The number of tokens available before the cooldown is to be applied.
"""
if not current:
current = time.time()
tokens = self._tokens
if current > self._window + self.per:
tokens = self.rate
return tokens
def get_retry_after(self, current: Optional[float] = None) -> float:
"""Returns the time in seconds until the cooldown will be reset.
Parameters
----------
current: Optional[:class:`float`]
The current time in seconds since Unix epoch.
If not supplied, then :func:`time.time()` is used.
Returns
-------
:class:`float`
The number of seconds to wait before this cooldown will be reset.
"""
current = current or time.time()
tokens = self.get_tokens(current)
if tokens == 0:
return self.per - (current - self._window)
return 0.0
def update_rate_limit(self, current: Optional[float] = None) -> Optional[float]:
"""Updates the cooldown rate limit.
Parameters
----------
current: Optional[:class:`float`]
The time in seconds since Unix epoch to update the rate limit at.
If not supplied, then :func:`time.time()` is used.
Returns
-------
Optional[:class:`float`]
The retry-after time in seconds if rate limited.
"""
current = current or time.time()
self._last = current
self._tokens = self.get_tokens(current)
# first token used means that we start a new rate limit window
if self._tokens == self.rate:
self._window = current
# check if we are rate limited
if self._tokens == 0:
return self.per - (current - self._window)
# we're not so decrement our tokens
self._tokens -= 1
return None
def reset(self) -> None:
"""Reset the cooldown to its initial state."""
self._tokens = self.rate
self._last = 0.0
def copy(self) -> Cooldown:
"""Creates a copy of this cooldown.
Returns
-------
:class:`Cooldown`
A new instance of this cooldown.
"""
return Cooldown(self.rate, self.per)
def __repr__(self) -> str:
return f"<Cooldown rate: {self.rate} per: {self.per} window: {self._window} tokens: {self._tokens}>"
class CooldownMapping:
def __init__(
self,
original: Optional[Cooldown],
type: Callable[[Message], Any],
) -> None:
if not callable(type):
raise TypeError("Cooldown type must be a BucketType or callable")
self._cache: Dict[Any, Cooldown] = {}
self._cooldown: Optional[Cooldown] = original
self._type: Callable[[Message], Any] = type
def copy(self) -> CooldownMapping:
ret = CooldownMapping(self._cooldown, self._type)
ret._cache = self._cache.copy()
return ret
def valid(self) -> bool:
return self._cooldown is not None
def type(self) -> Callable[[Message], Any]:
return self._type
def from_cooldown(cls, rate, per, type) -> Self:
return cls(Cooldown(rate, per), type)
def _bucket_key(self, msg: Message) -> Any:
return self._type(msg)
def _verify_cache_integrity(self, current: Optional[float] = None) -> None:
# we want to delete all cache objects that haven't been used
# in a cooldown window. e.g. if we have a command that has a
# cooldown of 60s and it has not been used in 60s then that key should be deleted
current = current or time.time()
dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
for k in dead_keys:
del self._cache[k]
def _is_default(self) -> bool:
# This method can be overridden in subclasses
return self._type is BucketType.default
def create_bucket(self, message: Message) -> Cooldown:
return self._cooldown.copy() # type: ignore
def get_bucket(self, message: Message, current: Optional[float] = None) -> Cooldown:
if self._is_default():
return self._cooldown # type: ignore
self._verify_cache_integrity(current)
key = self._bucket_key(message)
if key not in self._cache:
bucket = self.create_bucket(message)
self._cache[key] = bucket
else:
bucket = self._cache[key]
return bucket
def update_rate_limit(
self, message: Message, current: Optional[float] = None
) -> Optional[float]:
bucket = self.get_bucket(message, current)
return bucket.update_rate_limit(current)
class Message(Hashable):
r"""Represents a message from Discord.
.. container:: operations
.. describe:: x == y
Checks if two messages are equal.
.. describe:: x != y
Checks if two messages are not equal.
.. describe:: hash(x)
Returns the message's hash.
Attributes
----------
tts: :class:`bool`
Specifies if the message was done with text-to-speech.
This can only be accurately received in :func:`on_message` due to
a discord limitation.
type: :class:`MessageType`
The type of message. In most cases this should not be checked, but it is helpful
in cases where it might be a system message for :attr:`system_content`.
author: Union[:class:`Member`, :class:`abc.User`]
A :class:`Member` that sent the message. If :attr:`channel` is a
private channel or the user has the left the guild, then it is a :class:`User` instead.
content: :class:`str`
The actual contents of the message.
nonce: Optional[Union[:class:`str`, :class:`int`]]
The value used by the discord guild and the client to verify that the message is successfully sent.
This is not stored long term within Discord's servers and is only used ephemerally.
embeds: List[:class:`Embed`]
A list of embeds the message has.
channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`]
The :class:`TextChannel` or :class:`Thread` that the message was sent from.
Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message.
reference: Optional[:class:`~nextcord.MessageReference`]
The message that this message references. This is only applicable to messages of
type :attr:`MessageType.pins_add`, crossposted messages created by a
followed channel integration, or message replies.
.. versionadded:: 1.5
mention_everyone: :class:`bool`
Specifies if the message mentions everyone.
.. note::
This does not check if the ``@everyone`` or the ``@here`` text is in the message itself.
Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message
**and** it did end up mentioning.
mentions: List[:class:`abc.User`]
A list of :class:`Member` that were mentioned. If the message is in a private message
then the list will be of :class:`User` instead. For messages that are not of type
:attr:`MessageType.default`\, this array can be used to aid in system messages.
For more information, see :attr:`system_content`.
.. warning::
The order of the mentions list is not in any particular order so you should
not rely on it. This is a Discord limitation, not one with the library.
channel_mentions: List[:class:`abc.GuildChannel`]
A list of :class:`abc.GuildChannel` that were mentioned. If the message is in a private message
then the list is always empty.
role_mentions: List[:class:`Role`]
A list of :class:`Role` that were mentioned. If the message is in a private message
then the list is always empty.
id: :class:`int`
The message ID.
webhook_id: Optional[:class:`int`]
If this message was sent by a webhook, then this is the webhook ID's that sent this
message.
attachments: List[:class:`Attachment`]
A list of attachments given to a message.
pinned: :class:`bool`
Specifies if the message is currently pinned.
flags: :class:`MessageFlags`
Extra features of the message.
.. versionadded:: 1.3
reactions : List[:class:`Reaction`]
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
activity: Optional[:class:`dict`]
The activity associated with this message. Sent with Rich-Presence related messages that for
example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
- ``type``: An integer denoting the type of message activity being requested.
- ``party_id``: The party ID associated with the party.
application: Optional[:class:`dict`]
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
- ``id``: A string representing the application's ID.
- ``name``: A string representing the application's name.
- ``description``: A string representing the application's description.
- ``icon``: A string representing the icon ID of the application.
- ``cover_image``: A string representing the embed's image asset ID.
stickers: List[:class:`StickerItem`]
A list of sticker items given to the message.
.. versionadded:: 1.6
components: List[:class:`Component`]
A list of components in the message.
.. versionadded:: 2.0
guild: Optional[:class:`Guild`]
The guild that the message belongs to, if applicable.
interaction: Optional[:class:`MessageInteraction`]
The interaction data of a message, if applicable.
"""
__slots__ = (
"_state",
"_edited_timestamp",
"_cs_channel_mentions",
"_cs_raw_mentions",
"_cs_clean_content",
"_cs_raw_channel_mentions",
"_cs_raw_role_mentions",
"_cs_system_content",
"tts",
"content",
"channel",
"webhook_id",
"mention_everyone",
"embeds",
"id",
"interaction",
"mentions",
"author",
"attachments",
"nonce",
"pinned",
"role_mentions",
"type",
"flags",
"reactions",
"reference",
"application",
"activity",
"stickers",
"components",
"_background_tasks",
"guild",
)
if TYPE_CHECKING:
_HANDLERS: ClassVar[List[Tuple[str, Callable[..., None]]]]
_CACHED_SLOTS: ClassVar[List[str]]
guild: Optional[Guild]
reference: Optional[MessageReference]
mentions: List[Union[User, Member]]
author: Union[User, Member]
role_mentions: List[Role]
def __init__(
self,
*,
state: ConnectionState,
channel: MessageableChannel,
data: MessagePayload,
) -> None:
self._state: ConnectionState = state
self.id: int = int(data["id"])
self.webhook_id: Optional[int] = utils.get_as_snowflake(data, "webhook_id")
self.reactions: List[Reaction] = [
Reaction(message=self, data=d) for d in data.get("reactions", [])
]
self.attachments: List[Attachment] = [
Attachment(data=a, state=self._state) for a in data["attachments"]
]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data["embeds"]]
self.application: Optional[MessageApplicationPayload] = data.get("application")
self.activity: Optional[MessageActivityPayload] = data.get("activity")
self.channel: MessageableChannel = channel
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(
data["edited_timestamp"]
)
self.type: MessageType = try_enum(MessageType, data["type"])
self.pinned: bool = data["pinned"]
self.flags: MessageFlags = MessageFlags._from_value(data.get("flags", 0))
self.mention_everyone: bool = data["mention_everyone"]
self.tts: bool = data["tts"]
self.content: str = data["content"]
self.nonce: Optional[Union[int, str]] = data.get("nonce")
self.stickers: List[StickerItem] = [
StickerItem(data=d, state=state) for d in data.get("sticker_items", [])
]
self.components: List[Component] = [
_component_factory(d) for d in data.get("components", [])
]
self._background_tasks: Set[asyncio.Task[None]] = set()
try:
# if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild # type: ignore
except AttributeError:
if getattr(channel, "type", None) not in (ChannelType.group, ChannelType.private):
self.guild = state._get_guild(utils.get_as_snowflake(data, "guild_id"))
else:
self.guild = None
if (
(thread_data := data.get("thread"))
and not self.thread
and isinstance(self.guild, Guild)
):
self.guild._store_thread(thread_data)
try:
ref = data["message_reference"]
except KeyError:
self.reference = None
else:
self.reference = ref = MessageReference.with_state(state, ref)
try:
resolved = data["referenced_message"]
except KeyError:
pass
else:
if resolved is None:
ref.resolved = DeletedReferencedMessage(ref)
else:
# Right now the channel IDs match but maybe in the future they won't.
if ref.channel_id == channel.id:
chan = channel
else:
chan, _ = state._get_guild_channel(resolved)
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore
for handler in ("author", "member", "mentions", "mention_roles"):
try:
getattr(self, f"_handle_{handler}")(data[handler])
except KeyError:
continue
self.interaction: Optional[MessageInteraction] = (
MessageInteraction(data=data["interaction"], guild=self.guild, state=self._state)
if "interaction" in data
else None
)
def __repr__(self) -> str:
name = self.__class__.__name__
return f"<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>"
def _try_patch(self, data, key, transform=None) -> None:
try:
value = data[key]
except KeyError:
pass
else:
if transform is None:
setattr(self, key, value)
else:
setattr(self, key, transform(value))
def _add_reaction(self, data, emoji: Emoji | PartialEmoji | str, user_id) -> Reaction:
finder: Callable[[Reaction], bool] = lambda r: r.emoji == emoji
reaction = utils.find(finder, self.reactions)
is_me = data["me"] = user_id == self._state.self_id
if reaction is None:
reaction = Reaction(message=self, data=data, emoji=emoji)
self.reactions.append(reaction)
else:
reaction.count += 1
if is_me:
reaction.me = is_me
return reaction
def _remove_reaction(
self, data: ReactionPayload, emoji: EmojiInputType, user_id: int
) -> Reaction:
reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)
if reaction is None:
# already removed?
raise ValueError("Emoji already removed?")
# if reaction isn't in the list, we crash. This means discord
# sent bad data, or we stored improperly
reaction.count -= 1
if user_id == self._state.self_id:
reaction.me = False
if reaction.count == 0:
# this raises ValueError if something went wrong as well.
self.reactions.remove(reaction)
return reaction
def _clear_emoji(self, emoji) -> Optional[Reaction]:
to_check = str(emoji)
for index, reaction in enumerate(self.reactions): # noqa: B007
if str(reaction.emoji) == to_check:
break
else:
# didn't find anything so just return
return None
del self.reactions[index]
return reaction
def _update(self, data) -> None:
# In an update scheme, 'author' key has to be handled before 'member'
# otherwise they overwrite each other which is undesirable.
# Since there's no good way to do this we have to iterate over every
# handler rather than iterating over the keys which is a little slower
for key, handler in self._HANDLERS:
try:
value = data[key]
except KeyError:
continue
else:
handler(self, value)
# clear the cached properties
for attr in self._CACHED_SLOTS:
with contextlib.suppress(AttributeError):
delattr(self, attr)
def _handle_edited_timestamp(self, value: str) -> None:
self._edited_timestamp = utils.parse_time(value)
def _handle_pinned(self, value: bool) -> None:
self.pinned = value
def _handle_flags(self, value: int) -> None:
self.flags = MessageFlags._from_value(value)
def _handle_application(self, value: MessageApplicationPayload) -> None:
self.application = value
def _handle_activity(self, value: MessageActivityPayload) -> None:
self.activity = value
def _handle_mention_everyone(self, value: bool) -> None:
self.mention_everyone = value
def _handle_tts(self, value: bool) -> None:
self.tts = value
def _handle_type(self, value: int) -> None:
self.type = try_enum(MessageType, value)
def _handle_content(self, value: str) -> None:
self.content = value
def _handle_attachments(self, value: List[AttachmentPayload]) -> None:
self.attachments = [Attachment(data=a, state=self._state) for a in value]
def _handle_embeds(self, value: List[EmbedPayload]) -> None:
self.embeds = [Embed.from_dict(data) for data in value]
def _handle_nonce(self, value: Union[str, int]) -> None:
self.nonce = value
def _handle_author(self, author: UserPayload) -> None:
self.author = self._state.store_user(author)
if isinstance(self.guild, Guild):
found = self.guild.get_member(self.author.id)
if found is not None:
self.author = found
def _handle_member(self, member: MemberPayload) -> None:
# The gateway now gives us full Member objects sometimes with the following keys
# deaf, mute, joined_at, roles
# For the sake of performance I'm going to assume that the only
# field that needs *updating* would be the joined_at field.
# If there is no Member object (for some strange reason), then we can upgrade
# ourselves to a more "partial" member object.
author = self.author
try:
# Update member reference
author._update_from_message(member) # type: ignore
except AttributeError:
# It's a user here
# TODO: consider adding to cache here
self.author = Member._from_message(message=self, data=member)
def _handle_mentions(self, mentions: List[UserWithMemberPayload]) -> None:
self.mentions = r = []
guild = self.guild
state = self._state
if not isinstance(guild, Guild):
self.mentions = [state.store_user(m) for m in mentions]
return
for mention in filter(None, mentions):
id_search = int(mention["id"])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
else:
r.append(Member._try_upgrade(data=mention, guild=guild, state=state))
def _handle_mention_roles(self, role_mentions: List[int]) -> None:
self.role_mentions = []
if isinstance(self.guild, Guild):
for role_id in map(int, role_mentions):
role = self.guild.get_role(role_id)
if role is not None:
self.role_mentions.append(role)
def _handle_components(self, components: List[ComponentPayload]) -> None:
self.components = [_component_factory(d) for d in components]
def _handle_thread(self, thread: Optional[ThreadPayload]) -> None:
if thread:
self.guild._store_thread(thread) # type: ignore
def _rebind_cached_references(
self, new_guild: Guild, new_channel: Union[TextChannel, Thread]
) -> None:
self.guild = new_guild
self.channel = new_channel
def raw_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of user IDs matched with
the syntax of ``<@user_id>`` in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return utils.parse_raw_mentions(self.content)
def raw_channel_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of channel IDs matched with
the syntax of ``<#channel_id>`` in the message content.
"""
return utils.parse_raw_channel_mentions(self.content)
def raw_role_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of role IDs matched with
the syntax of ``<@&role_id>`` in the message content.
"""
return utils.parse_raw_role_mentions(self.content)
def channel_mentions(self) -> List[GuildChannel]:
if self.guild is None:
return []
it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions))
return utils.unique(it)
def clean_content(self) -> str:
""":class:`str`: A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* affect markdown. If you want to escape
or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown`
respectively, along with this function.
"""
transformations = {
re.escape(f"<#{channel.id}>"): "#" + channel.name for channel in self.channel_mentions
}
mention_transforms = {
re.escape(f"<@{member.id}>"): "@" + member.display_name for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape(f"<@!{member.id}>"): "@" + member.display_name for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape(f"<@&{role.id}>"): "@" + role.name for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), "")
pattern = re.compile("|".join(transformations.keys()))
result = pattern.sub(repl, self.content)
return escape_mentions(result)
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The message's creation time in UTC."""
return utils.snowflake_time(self.id)
def edited_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: An aware UTC datetime object containing the edited time of the message."""
return self._edited_timestamp
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this message."""
guild_id = getattr(self.guild, "id", "@me")
return f"https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}"
def thread(self) -> Optional[Thread]:
"""Optional[:class:`Thread`]: The thread started from this message. None if no thread was started."""
if not isinstance(self.guild, Guild):
return None
return self.guild.get_thread(self.id)
def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API
in response to something.
.. versionadded:: 1.3
"""
return self.type not in (
MessageType.default,
MessageType.reply,
MessageType.chat_input_command,
MessageType.context_menu_command,
MessageType.thread_starter_message,
)
def system_content(self):
r""":class:`str`: A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default` and :attr:`MessageType.reply`\,
this just returns the regular :attr:`Message.content`. Otherwise this
returns an English message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.recipient_add:
if self.channel.type is ChannelType.group:
return f"{self.author.name} added {self.mentions[0].name} to the group."
return f"{self.author.name} added {self.mentions[0].name} to the thread."
if self.type is MessageType.recipient_remove:
if self.channel.type is ChannelType.group:
return f"{self.author.name} removed {self.mentions[0].name} from the group."
return f"{self.author.name} removed {self.mentions[0].name} from the thread."
if self.type is MessageType.channel_name_change:
return f"{self.author.name} changed the channel name: **{self.content}**"
if self.type is MessageType.channel_icon_change:
return f"{self.author.name} changed the channel icon."
if self.type is MessageType.pins_add:
return f"{self.author.name} pinned a message to this channel."
if self.type is MessageType.new_member:
formats = [
"{0} joined the party.",
"{0} is here.",
"Welcome, {0}. We hope you brought pizza.",
"A wild {0} appeared.",
"{0} just landed.",
"{0} just slid into the server.",
"{0} just showed up!",
"Welcome {0}. Say hi!",
"{0} hopped into the server.",
"Everyone welcome {0}!",
"Glad you're here, {0}.",
"Good to see you, {0}.",
"Yay you made it, {0}!",
]
created_at_ms = int(self.created_at.timestamp() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.premium_guild_subscription:
if not self.content:
return f"{self.author.name} just boosted the server!"
return f"{self.author.name} just boosted the server **{self.content}** times!"
if self.type is MessageType.premium_guild_tier_1:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**"
if self.type is MessageType.premium_guild_tier_2:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**"
if self.type is MessageType.premium_guild_tier_3:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**"
if self.type is MessageType.channel_follow_add:
return f"{self.author.name} has added {self.content} to this channel"
if self.type is MessageType.guild_stream:
# the author will be a Member
return f"{self.author.name} is live! Now streaming {self.author.activity.name}" # type: ignore
if self.type is MessageType.guild_discovery_disqualified:
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details."
if self.type is MessageType.guild_discovery_requalified:
return "This server is eligible for Server Discovery again and has been automatically relisted!"
if self.type is MessageType.guild_discovery_grace_period_initial_warning:
return "This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery."
if self.type is MessageType.guild_discovery_grace_period_final_warning:
return "This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery."
if self.type is MessageType.thread_created:
return f"{self.author.name} started a thread: **{self.content}**. See all **threads**."
if self.type is MessageType.reply:
return self.content
if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None:
return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore
if self.type is MessageType.guild_invite_reminder:
return "Wondering who to invite?\nStart by inviting anyone who can help you build the server!"
if self.type is MessageType.stage_start:
return f"{self.author.display_name} started {self.content}"
if self.type is MessageType.stage_end:
return f"{self.author.display_name} ended {self.content}"
if self.type is MessageType.stage_speaker:
return f"{self.author.display_name} is now a speaker."
if self.type is MessageType.stage_topic:
return f"{self.author.display_name} changed the Stage topic: {self.content}"
return None
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1
Added the new ``delay`` keyword-only parameter.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message. If the deletion fails then it is silently ignored.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
NotFound
The message was deleted already
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete(delay: float) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await self._state.http.delete_message(self.channel.id, self.id)
task = asyncio.create_task(delete(delay))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await self._state.http.delete_message(self.channel.id, self.id)
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
content: Optional[str] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: List[Embed] = MISSING,
attachments: List[Attachment] = MISSING,
suppress: bool = MISSING,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
view: Optional[View] = MISSING,
file: Optional[File] = MISSING,
files: Optional[List[File]] = MISSING,
) -> Message:
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
.. versionchanged:: 1.3
The ``suppress`` keyword-only parameter was added.
Parameters
----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
embeds: List[:class:`Embed`]
The new embeds to replace the original with. Must be a maximum of 10.
To remove all embeds ``[]`` should be passed.
.. versionadded:: 2.0
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep all existing attachments,
pass ``message.attachments``.
suppress: :class:`bool`
Whether to suppress embeds for the message. This removes
all the embeds if set to ``True``. If set to ``False``
this brings the embeds back if they were suppressed.
Using this parameter requires :attr:`~.Permissions.manage_messages`.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~nextcord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~nextcord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~nextcord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~nextcord.Client.allowed_mentions`
are used instead.
.. versionadded:: 1.4
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
file: Optional[:class:`File`]
If provided, a new file to add to the message.
.. versionadded:: 2.0
files: Optional[List[:class:`File`]]
If provided, a list of new files to add to the message.
.. versionadded:: 2.0
Raises
------
HTTPException
Editing the message failed.
Forbidden
Tried to suppress a message without permissions or
edited a message's content or embed that isn't yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
Returns
-------
:class:`Message`
The edited message.
"""
payload: Dict[str, Any] = {}
if content is not MISSING:
if content is not None:
payload["content"] = str(content)
else:
payload["content"] = None
if embed is not MISSING and embeds is not MISSING:
raise InvalidArgument("Cannot pass both embed and embeds parameter to edit()")
if file is not MISSING and files is not MISSING:
raise InvalidArgument("Cannot pass both file and files parameter to edit()")
if embed is not MISSING:
if embed is None:
payload["embeds"] = []
else:
payload["embeds"] = [embed.to_dict()]
elif embeds is not MISSING:
payload["embeds"] = [e.to_dict() for e in embeds]
if suppress is not MISSING:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = suppress
payload["flags"] = flags.value
if allowed_mentions is MISSING:
if self._state.allowed_mentions is not None and self.author.id == self._state.self_id:
payload["allowed_mentions"] = self._state.allowed_mentions.to_dict()
elif allowed_mentions is not None:
if self._state.allowed_mentions is not None:
payload["allowed_mentions"] = self._state.allowed_mentions.merge(
allowed_mentions
).to_dict()
else:
payload["allowed_mentions"] = allowed_mentions.to_dict()
if attachments is not MISSING:
payload["attachments"] = [a.to_dict() for a in attachments]
if view is not MISSING:
self._state.prevent_view_updates_for(self.id)
if view:
payload["components"] = view.to_components()
else:
payload["components"] = []
if file is not MISSING:
payload["files"] = [file]
elif files is not MISSING:
payload["files"] = files
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
message = Message(state=self._state, channel=self.channel, data=data)
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, self.id)
if delete_after is not None:
await self.delete(delay=delete_after)
return message
async def publish(self) -> None:
"""|coro|
Publishes this message to your announcement channel.
You must have the :attr:`~Permissions.send_messages` permission to do this.
If the message is not your own then the :attr:`~Permissions.manage_messages`
permission is also needed.
Raises
------
Forbidden
You do not have the proper permissions to publish this message.
HTTPException
Publishing the message failed.
"""
await self._state.http.publish_message(self.channel.id, self.id)
async def pin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for pinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id, reason=reason)
self.pinned = True
async def unpin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for unpinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id, reason=reason)
self.pinned = False
async def add_reaction(self, emoji: EmojiInputType) -> None:
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
async def remove_reaction(
self, emoji: Union[EmojiInputType, Reaction], member: Snowflake
) -> None:
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:
"""|coro|
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You need the :attr:`~Permissions.manage_messages` permission to use this.
.. versionadded:: 1.3
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to clear.
Raises
------
HTTPException
Clearing the reaction failed.
Forbidden
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji)
async def clear_reactions(self) -> None:
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
async def create_thread(
self, *, name: str, auto_archive_duration: ThreadArchiveDuration = MISSING
) -> Thread:
"""|coro|
Creates a public thread from this message.
You must have :attr:`~nextcord.Permissions.create_public_threads` in order to
create a public thread from a message.
The channel this message belongs in must be a :class:`TextChannel`.
.. versionadded:: 2.0
Parameters
----------
name: :class:`str`
The name of the thread.
auto_archive_duration: :class:`int`
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
Raises
------
Forbidden
You do not have permissions to create a thread.
HTTPException
Creating the thread failed.
InvalidArgument
This message does not have guild info attached.
Returns
-------
:class:`.Thread`
The created thread.
"""
if self.guild is None:
raise InvalidArgument("This message does not have guild info attached.")
default_auto_archive_duration: ThreadArchiveDuration = getattr(
self.channel, "default_auto_archive_duration", 1440
)
data = await self._state.http.start_thread_with_message(
self.channel.id,
self.id,
name=name,
auto_archive_duration=auto_archive_duration or default_auto_archive_duration,
)
return Thread(guild=self.guild, state=self._state, data=data)
async def reply(self, content: Optional[str] = None, **kwargs) -> Message:
"""|coro|
A shortcut method to :meth:`.abc.Messageable.send` to reply to the
:class:`.Message`.
.. versionadded:: 1.6
Raises
------
~nextcord.HTTPException
Sending the message failed.
~nextcord.Forbidden
You do not have the proper permissions to send the message.
~nextcord.InvalidArgument
The ``files`` list is not of the appropriate size or
you specified both ``file`` and ``files``.
Returns
-------
:class:`.Message`
The message that was sent.
"""
return await self.channel.send(content, reference=self, **kwargs)
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a :class:`~nextcord.MessageReference` from the current message.
.. versionadded:: 1.6
Parameters
----------
fail_if_not_exists: :class:`bool`
Whether replying using the message reference should raise :class:`HTTPException`
if the message no longer exists or Discord could not fetch the message.
.. versionadded:: 1.7
Returns
-------
:class:`~nextcord.MessageReference`
The reference to this message.
"""
return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists)
def to_message_reference_dict(self) -> MessageReferencePayload:
data: MessageReferencePayload = {
"message_id": self.id,
"channel_id": self.channel.id,
}
if self.guild is not None:
data["guild_id"] = self.guild.id
return data
CoroFunc = Callable[..., Coro[Any]]
The provided code snippet includes necessary dependencies for implementing the `cooldown` function. Write a Python function `def cooldown( rate: int, per: float, type: Union[BucketType, Callable[[Message], Any]] = BucketType.default ) -> Callable[[T], T]` to solve the following problem:
A decorator that adds a cooldown to a :class:`.Command` A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. Parameters ---------- rate: :class:`int` The number of times a command can be used before triggering a cooldown. per: :class:`float` The amount of seconds to wait for a cooldown when it's been triggered. type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]] The type of cooldown to have. If callable, should return a key for the mapping. .. versionchanged:: 1.7 Callables are now supported for custom bucket types.
Here is the function:
def cooldown(
rate: int, per: float, type: Union[BucketType, Callable[[Message], Any]] = BucketType.default
) -> Callable[[T], T]:
"""A decorator that adds a cooldown to a :class:`.Command`
A cooldown allows a command to only be used a specific amount
of times in a specific time frame. These cooldowns can be based
either on a per-guild, per-channel, per-user, per-role or global basis.
Denoted by the third argument of ``type`` which must be of enum
type :class:`.BucketType`.
If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in
:func:`.on_command_error` and the local error handler.
A command can only have a single cooldown.
Parameters
----------
rate: :class:`int`
The number of times a command can be used before triggering a cooldown.
per: :class:`float`
The amount of seconds to wait for a cooldown when it's been triggered.
type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]]
The type of cooldown to have. If callable, should return a key for the mapping.
.. versionchanged:: 1.7
Callables are now supported for custom bucket types.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func._buckets = CooldownMapping(Cooldown(rate, per), type)
else:
func.__commands_cooldown__ = CooldownMapping(Cooldown(rate, per), type)
return func
return decorator # type: ignore | A decorator that adds a cooldown to a :class:`.Command` A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. Parameters ---------- rate: :class:`int` The number of times a command can be used before triggering a cooldown. per: :class:`float` The amount of seconds to wait for a cooldown when it's been triggered. type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]] The type of cooldown to have. If callable, should return a key for the mapping. .. versionchanged:: 1.7 Callables are now supported for custom bucket types. |
160,905 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
class Command(_BaseCommand, Generic[CogT, P, T]):
r"""A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The coroutine that is executed when the command is called.
help: Optional[:class:`str`]
The long help text for the command.
brief: Optional[:class:`str`]
The short help text for the command.
usage: Optional[:class:`str`]
A replacement for arguments in the default help text.
aliases: Union[List[:class:`str`], Tuple[:class:`str`]]
The list of aliases the command can be invoked under.
enabled: :class:`bool`
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
:exc:`.DisabledCommand` is raised to the :func:`.on_command_error`
event. Defaults to ``True``.
parent: Optional[:class:`Group`]
The parent group that this command belongs to. ``None`` if there
isn't one.
cog: Optional[:class:`Cog`]
The cog that this command belongs to. ``None`` if there isn't one.
checks: List[Callable[[:class:`.Context`], :class:`bool`]]
A list of predicates that verifies if the command could be executed
with the given :class:`.Context` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.CommandError` should be used. Note that if the checks fail then
:exc:`.CheckFailure` exception is raised to the :func:`.on_command_error`
event.
description: :class:`str`
The message prefixed into the default help command.
hidden: :class:`bool`
If ``True``\, the default help command does not show this in the
help output.
rest_is_raw: :class:`bool`
If ``False`` and a keyword-only argument is provided then the keyword
only argument is stripped and handled as if it was a regular argument
that handles :exc:`.MissingRequiredArgument` and default values in a
regular matter rather than passing the rest completely raw. If ``True``
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults to ``False``.
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked, if any.
require_var_positional: :class:`bool`
If ``True`` and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults to ``False``.
.. versionadded:: 1.5
ignore_extra: :class:`bool`
If ``True``\, ignores extraneous strings passed to a command if all its
requirements are met (e.g. ``?foo a b c`` when only expecting ``a``
and ``b``). Otherwise :func:`.on_command_error` and local error handlers
are called with :exc:`.TooManyArguments`. Defaults to ``True``.
cooldown_after_parsing: :class:`bool`
If ``True``\, cooldown processing is done after argument parsing,
which calls converters. If ``False`` then cooldown processing is done
first and then the converters are called second. Defaults to ``False``.
extras: :class:`dict`
A dict of user provided extras to attach to the Command.
.. note::
This object may be copied by the library.
.. versionadded:: 2.0
inherit_hooks: :class:`bool`
If ``True`` and this command has a parent :class:`Group` then this command
will inherit all checks, pre_invoke and after_invoke's defined on the the :class:`Group`
This defaults to ``False``
.. note::
Any ``pre_invoke`` or ``after_invoke``'s defined on this will override parent ones.
.. versionadded:: 2.0.0
"""
__original_kwargs__: Dict[str, Any]
def __new__(cls, *_args: Any, **kwargs: Any) -> Self:
# if you're wondering why this is done, it's because we need to ensure
# we have a complete original copy of **kwargs even for classes that
# mess with it by popping before delegating to the subclass __init__.
# In order to do this, we need to control the instance creation and
# inject the original kwargs through __new__ rather than doing it
# inside __init__.
self = super().__new__(cls)
# we do a shallow copy because it's probably the most common use case.
# this could potentially break if someone modifies a list or something
# while it's in movement, but for now this is the cheapest and
# fastest way to do what we want.
self.__original_kwargs__ = kwargs.copy()
return self
def __init__(
self,
func: Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
],
**kwargs: Any,
) -> None:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine.")
name = kwargs.get("name") or func.__name__
if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
self.name: str = name
# ContextT is incompatible with normal Context
self.callback = func # pyright: ignore
self.enabled: bool = kwargs.get("enabled", True)
help_doc = kwargs.get("help")
if help_doc is not None:
help_doc = inspect.cleandoc(help_doc)
else:
help_doc = inspect.getdoc(func)
if isinstance(help_doc, bytes):
help_doc = help_doc.decode("utf-8")
self.help: Optional[str] = help_doc
self.brief: Optional[str] = kwargs.get("brief")
self.usage: Optional[str] = kwargs.get("usage")
self.rest_is_raw: bool = kwargs.get("rest_is_raw", False)
self.aliases: Union[List[str], Tuple[str]] = kwargs.get("aliases", [])
self.extras: Dict[str, Any] = kwargs.get("extras", {})
if not isinstance(self.aliases, (list, tuple)):
raise TypeError("Aliases of a command must be a list or a tuple of strings.")
self.description: str = inspect.cleandoc(kwargs.get("description", ""))
self.hidden: bool = kwargs.get("hidden", False)
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks: List[Check] = checks
try:
cooldown = func.__commands_cooldown__
except AttributeError:
cooldown = kwargs.get("cooldown")
if cooldown is None:
buckets = CooldownMapping(cooldown, BucketType.default)
elif isinstance(cooldown, CooldownMapping):
buckets = cooldown
else:
raise TypeError("Cooldown must be an instance of CooldownMapping or None.")
self._buckets: CooldownMapping = buckets
try:
max_concurrency = func.__commands_max_concurrency__
except AttributeError:
max_concurrency = kwargs.get("max_concurrency")
self._max_concurrency: Optional[MaxConcurrency] = max_concurrency
self.require_var_positional: bool = kwargs.get("require_var_positional", False)
self.ignore_extra: bool = kwargs.get("ignore_extra", True)
self.cooldown_after_parsing: bool = kwargs.get("cooldown_after_parsing", False)
self.cog: Optional[CogT] = None
# bandaid for the fact that sometimes parent can be the bot instance
parent = kwargs.get("parent")
self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore
self._before_invoke: Optional[Hook] = None
try:
before_invoke = func.__before_invoke__
except AttributeError:
pass
else:
self.before_invoke(before_invoke)
self._after_invoke: Optional[Hook] = None
try:
after_invoke = func.__after_invoke__
except AttributeError:
pass
else:
self.after_invoke(after_invoke)
# Attempt to bind to parent hooks if applicable
if not kwargs.get("inherit_hooks", False):
return
# We should be binding hooks
if not self.parent:
return
inherited_before_invoke: Optional[Hook] = None
try:
inherited_before_invoke = self.parent._before_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_before_invoke:
self.before_invoke(inherited_before_invoke)
inherited_after_invoke: Optional[Hook] = None
try:
inherited_after_invoke = self.parent._after_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_after_invoke:
self.after_invoke(inherited_after_invoke)
self.checks.extend(self.parent.checks) # type: ignore
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_guild_permissions", {})
def callback(
self,
) -> Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]:
return self._callback
def callback(
self,
function: Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
],
) -> None:
self._callback = function
unwrap = unwrap_function(function)
self.module = unwrap.__module__
try:
globalns = unwrap.__globals__
except AttributeError:
globalns = {}
self.params = get_signature_parameters(function, globalns)
def add_check(self, func: Check) -> None:
"""Adds a check to the command.
This is the non-decorator interface to :func:`.check`.
.. versionadded:: 1.3
Parameters
----------
func
The function that will be used as a check.
"""
self.checks.append(func)
def remove_check(self, func: Check) -> None:
"""Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command's checks.
.. versionadded:: 1.3
Parameters
----------
func
The function to remove from the checks.
"""
with contextlib.suppress(ValueError):
self.checks.remove(func)
def update(self, **kwargs: Any) -> None:
"""Updates :class:`Command` instance with updated attribute.
This works similarly to the :func:`.command` decorator in terms
of parameters in that they are passed to the :class:`Command` or
subclass constructors, sans the name and callback.
"""
self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs))
async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T:
"""|coro|
Calls the internal callback that the command holds.
.. note::
This bypasses all mechanisms -- including checks, converters,
invoke hooks, cooldowns, etc. You must take care to pass
the proper arguments and types to this function.
.. versionadded:: 1.3
"""
if self.cog is not None:
return await self.callback(self.cog, context, *args, **kwargs) # type: ignore
return await self.callback(context, *args, **kwargs) # type: ignore
def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT:
other._before_invoke = self._before_invoke
other._after_invoke = self._after_invoke
if self.checks != other.checks:
other.checks = self.checks.copy()
if self._buckets.valid and not other._buckets.valid:
other._buckets = self._buckets.copy()
if self._max_concurrency != other._max_concurrency:
# _max_concurrency won't be None at this point
other._max_concurrency = self._max_concurrency.copy() # type: ignore
with contextlib.suppress(AttributeError):
other.on_error = self.on_error
return other
def copy(self) -> Self:
"""Creates a copy of this command.
Returns
-------
:class:`Command`
A new instance of this command.
"""
ret = self.__class__(self.callback, **self.__original_kwargs__)
return self._ensure_assignment_on_copy(ret)
def _update_copy(self, kwargs: Dict[str, Any]) -> Self:
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = self.__class__(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
return self.copy()
async def dispatch_error(self, ctx: Context, error: Exception) -> None:
ctx.command_failed = True
cog = self.cog
try:
coro = self.on_error
except AttributeError:
pass
else:
injected = wrap_callback(coro)
if cog is not None:
await injected(cog, ctx, error)
else:
await injected(ctx, error)
try:
if cog is not None:
local = Cog._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch("command_error", ctx, error)
async def transform(self, ctx: Context, param: inspect.Parameter) -> Any:
required = param.default is param.empty
converter = get_converter(param)
consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw
view = ctx.view
view.skip_ws()
# The greedy converter is simple -- it keeps going until it fails in which case,
# it undos the view ready for the next parameter to use instead
if isinstance(converter, Greedy):
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
return await self._transform_greedy_pos(ctx, param, required, converter.converter)
if param.kind == param.VAR_POSITIONAL:
return await self._transform_greedy_var_pos(ctx, param, converter.converter)
# if we're here, then it's a KEYWORD_ONLY param type
# since this is mostly useless, we'll helpfully transform Greedy[X]
# into just X and do the parsing that way.
converter = converter.converter
if view.eof:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError # break the loop
if required:
if self._is_typing_optional(param.annotation):
return None
if hasattr(converter, "__commands_is_flag__") and converter._can_be_constructible():
return await converter._construct_default(ctx)
raise MissingRequiredArgument(param)
return param.default
previous = view.index
if consume_rest_is_special:
argument = view.read_rest().strip()
else:
try:
argument = view.get_quoted_word()
except ArgumentParsingError:
if self._is_typing_optional(param.annotation):
view.index = previous
return None
raise
view.previous = previous
if argument is None:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError
if required:
if self._is_typing_optional(param.annotation):
return None
raise MissingRequiredArgument(param)
return param.default
# type-checker fails to narrow argument
return await run_converters(ctx, converter, argument, param)
async def _transform_greedy_pos(
self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any
) -> Any:
view = ctx.view
result = []
while not view.eof:
# for use with a manual undo
previous = view.index
view.skip_ws()
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
break
else:
result.append(value)
if not result and not required:
return param.default
return result
async def _transform_greedy_var_pos(
self, ctx: Context, param: inspect.Parameter, converter: Any
) -> Any:
view = ctx.view
previous = view.index
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
raise RuntimeError from None # break loop
else:
return value
def clean_params(self) -> Dict[str, inspect.Parameter]:
"""Dict[:class:`str`, :class:`inspect.Parameter`]:
Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'self' parameter") from None
try:
# first/second parameter is context
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'context' parameter") from None
return result
def full_parent_name(self) -> str:
""":class:`str`: Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``.
"""
entries = []
command = self
# command.parent is type-hinted as GroupMixin some attributes are resolved via MRO
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command.name) # type: ignore
return " ".join(reversed(entries))
def parents(self) -> List[Group]:
"""List[:class:`Group`]: Retrieves the parents of this command.
If the command has no parents then it returns an empty :class:`list`.
For example in commands ``?a b c test``, the parents are ``[c, b, a]``.
.. versionadded:: 1.1
"""
entries = []
command = self
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command)
return entries
def root_parent(self) -> Optional[Group]:
"""Optional[:class:`Group`]: Retrieves the root parent of this command.
If the command has no parents then it returns ``None``.
For example in commands ``?a b c test``, the root parent is ``a``.
"""
if not self.parent:
return None
return self.parents[-1]
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return parent + " " + self.name
return self.name
def __str__(self) -> str:
return self.qualified_name
async def _parse_arguments(self, ctx: Context) -> None:
ctx.args = [ctx] if self.cog is None else [self.cog, ctx]
ctx.kwargs = {}
args = ctx.args
kwargs = ctx.kwargs
view = ctx.view
iterator = iter(self.params.items())
if self.cog is not None:
# we have 'self' as the first parameter so just advance
# the iterator and resume parsing
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "self" parameter.'
) from None
# next we have the 'ctx' as the next parameter
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "ctx" parameter.'
) from None
for name, param in iterator:
ctx.current_parameter = param
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
transformed = await self.transform(ctx, param)
args.append(transformed)
elif param.kind == param.KEYWORD_ONLY:
# kwarg only param denotes "consume rest" semantics
if self.rest_is_raw:
converter = get_converter(param)
argument = view.read_rest()
kwargs[name] = await run_converters(ctx, converter, argument, param)
else:
kwargs[name] = await self.transform(ctx, param)
break
elif param.kind == param.VAR_POSITIONAL:
if view.eof and self.require_var_positional:
raise MissingRequiredArgument(param)
while not view.eof:
try:
transformed = await self.transform(ctx, param)
args.append(transformed)
except RuntimeError:
break
if not self.ignore_extra and not view.eof:
raise TooManyArguments("Too many arguments passed to " + self.qualified_name)
async def call_before_hooks(self, ctx: Context) -> None:
# now that we're done preparing we can call the pre-command hooks
# first, call the command local hook:
cog = self.cog
if self._before_invoke is not None:
# should be cog if @commands.before_invoke is used
instance = getattr(self._before_invoke, "__self__", cog)
# __self__ only exists for methods, not functions
# however, if @command.before_invoke is used, it will be a function
if instance:
await self._before_invoke(instance, ctx) # type: ignore
else:
await self._before_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_before_invoke)
if hook is not None:
await hook(ctx)
# call the bot global hook if necessary
hook = ctx.bot._before_invoke
if hook is not None:
await hook(ctx)
async def call_after_hooks(self, ctx: Context) -> None:
cog = self.cog
if self._after_invoke is not None:
instance = getattr(self._after_invoke, "__self__", cog)
if instance:
await self._after_invoke(instance, ctx) # type: ignore
else:
await self._after_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
def _prepare_cooldowns(self, ctx: Context) -> None:
if self._buckets.valid:
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
bucket = self._buckets.get_bucket(ctx.message, current)
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
async def prepare(self, ctx: Context) -> None:
ctx.command = self
if not await self.can_run(ctx):
raise CheckFailure(f"The check functions for command {self.qualified_name} failed.")
if self._max_concurrency is not None:
# For this application, context can be duck-typed as a Message
await self._max_concurrency.acquire(ctx) # type: ignore
try:
if self.cooldown_after_parsing:
await self._parse_arguments(ctx)
self._prepare_cooldowns(ctx)
else:
self._prepare_cooldowns(ctx)
await self._parse_arguments(ctx)
await self.call_before_hooks(ctx)
except:
if self._max_concurrency is not None:
await self._max_concurrency.release(ctx) # type: ignore
raise
def is_on_cooldown(self, ctx: Context) -> bool:
"""Checks whether the command is currently on cooldown.
Parameters
----------
ctx: :class:`.Context`
The invocation context to use when checking the commands cooldown status.
Returns
-------
:class:`bool`
A boolean indicating if the command is on cooldown.
"""
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_tokens(current) == 0
def reset_cooldown(self, ctx: Context) -> None:
"""Resets the cooldown on this command.
Parameters
----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.reset()
def get_cooldown_retry_after(self, ctx: Context) -> float:
"""Retrieves the amount of seconds before this command can be tried again.
.. versionadded:: 1.4
Parameters
----------
ctx: :class:`.Context`
The invocation context to retrieve the cooldown from.
Returns
-------
:class:`float`
The amount of time left on this command's cooldown in seconds.
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_retry_after(current)
return 0.0
async def invoke(self, ctx: Context) -> None:
await self.prepare(ctx)
# terminate the invoked_subcommand chain.
# since we're in a regular command (and not a group) then
# the invoked subcommand is None.
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
ctx.invoked_subcommand = None
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
def error(self, coro: ErrorT) -> ErrorT:
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The error handler must be a coroutine.")
self.on_error: Error = coro
return coro
def has_error_handler(self) -> bool:
""":class:`bool`: Checks whether the command has an error handler registered.
.. versionadded:: 1.7
"""
return hasattr(self, "on_error")
def before_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The pre-invoke hook must be a coroutine.")
self._before_invoke = coro
return coro
def after_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The post-invoke hook must be a coroutine.")
self._after_invoke = coro
return coro
def cog_name(self) -> Optional[str]:
"""Optional[:class:`str`]: The name of the cog this command belongs to, if any."""
return type(self.cog).__cog_name__ if self.cog is not None else None
def short_doc(self) -> str:
""":class:`str`: Gets the "short" documentation of a command.
By default, this is the :attr:`.brief` attribute.
If that lookup leads to an empty string then the first line of the
:attr:`.help` attribute is used instead.
"""
if self.brief is not None:
return self.brief
if self.help is not None:
return self.help.split("\n", 1)[0]
return ""
def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]:
return getattr(annotation, "__origin__", None) is Union and type(None) in annotation.__args__ # type: ignore
def signature(self) -> str:
""":class:`str`: Returns a POSIX-like signature useful for help command output."""
if self.usage is not None:
return self.usage
params = self.clean_params
if not params:
return ""
result = []
for name, param in params.items():
greedy = isinstance(param.annotation, Greedy)
optional = False # postpone evaluation of if it's an optional argument
# for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the
# parameter signature is a literal list of it's values
annotation = param.annotation.converter if greedy else param.annotation
origin = getattr(annotation, "__origin__", None)
if not greedy and origin is Union:
none_cls = type(None)
union_args = annotation.__args__
optional = union_args[-1] is none_cls
if len(union_args) == 2 and optional:
annotation = union_args[0]
origin = getattr(annotation, "__origin__", None)
if origin is Literal:
name = "|".join(
f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__
)
if param.default is not param.empty:
# We don't want None or '' to trigger the [name=value] case and instead it should
# do [name] since [name=None] or [name=] are not exactly useful for the user.
should_print = (
param.default if isinstance(param.default, str) else param.default is not None
)
if should_print:
result.append(
f"[{name}={param.default}]"
if not greedy
else f"[{name}={param.default}]..."
)
continue
result.append(f"[{name}]")
elif param.kind == param.VAR_POSITIONAL:
if self.require_var_positional:
result.append(f"<{name}...>")
else:
result.append(f"[{name}...]")
elif greedy:
result.append(f"[{name}]...")
elif optional:
result.append(f"[{name}]")
else:
result.append(f"<{name}>")
return " ".join(result)
async def can_run(self, ctx: Context) -> bool:
"""|coro|
Checks if the command can be executed by checking all the predicates
inside the :attr:`~Command.checks` attribute. This also checks whether the
command is disabled.
.. versionchanged:: 1.3
Checks whether the command is disabled or not
Parameters
----------
ctx: :class:`.Context`
The ctx of the command currently being invoked.
Raises
------
:class:`CommandError`
Any command error that was raised during a check call will be propagated
by this function.
Returns
-------
:class:`bool`
A boolean indicating if the command can be invoked.
"""
if not self.enabled:
raise DisabledCommand(f"{self.name} command is disabled")
original = ctx.command
ctx.command = self
try:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.qualified_name} failed."
)
cog = self.cog
if cog is not None:
local_check = Cog._get_overridden_method(cog.cog_check)
if local_check is not None:
ret = await nextcord.utils.maybe_coroutine(local_check, ctx)
if not ret:
return False
predicates = self.checks
if not predicates:
# since we have no checks, then we just return True.
return True
return await nextcord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
finally:
ctx.command = original
class BucketType(IntEnum):
default = 0
user = 1
guild = 2
channel = 3
member = 4
category = 5
role = 6
def get_key(self, msg: Message) -> Any:
if self is BucketType.user:
return msg.author.id
if self is BucketType.guild:
return (msg.guild or msg.author).id
if self is BucketType.channel:
return msg.channel.id
if self is BucketType.member:
return ((msg.guild and msg.guild.id), msg.author.id)
if self is BucketType.category:
return (msg.channel.category or msg.channel).id # type: ignore
if self is BucketType.role:
# we return the channel id of a private-channel as there are only roles in guilds
# and that yields the same result as for a guild with only the @everyone role
# NOTE: PrivateChannel doesn't actually have an id attribute but we assume we are
# recieving a DMChannel or GroupChannel which inherit from PrivateChannel and do
return (msg.channel if isinstance(msg.channel, PrivateChannel) else msg.author.top_role).id # type: ignore
return None
def __call__(self, msg: Message) -> Any:
return self.get_key(msg)
class DynamicCooldownMapping(CooldownMapping):
def __init__(
self, factory: Callable[[Message], Cooldown], type: Callable[[Message], Any]
) -> None:
super().__init__(None, type)
self._factory: Callable[[Message], Cooldown] = factory
def copy(self) -> DynamicCooldownMapping:
ret = DynamicCooldownMapping(self._factory, self._type)
ret._cache = self._cache.copy()
return ret
def valid(self) -> bool:
return True
def _is_default(self) -> bool:
# In dynamic mappings even default bucket types may have custom behavior
return False
def create_bucket(self, message: Message) -> Cooldown:
return self._factory(message)
class Message(Hashable):
r"""Represents a message from Discord.
.. container:: operations
.. describe:: x == y
Checks if two messages are equal.
.. describe:: x != y
Checks if two messages are not equal.
.. describe:: hash(x)
Returns the message's hash.
Attributes
----------
tts: :class:`bool`
Specifies if the message was done with text-to-speech.
This can only be accurately received in :func:`on_message` due to
a discord limitation.
type: :class:`MessageType`
The type of message. In most cases this should not be checked, but it is helpful
in cases where it might be a system message for :attr:`system_content`.
author: Union[:class:`Member`, :class:`abc.User`]
A :class:`Member` that sent the message. If :attr:`channel` is a
private channel or the user has the left the guild, then it is a :class:`User` instead.
content: :class:`str`
The actual contents of the message.
nonce: Optional[Union[:class:`str`, :class:`int`]]
The value used by the discord guild and the client to verify that the message is successfully sent.
This is not stored long term within Discord's servers and is only used ephemerally.
embeds: List[:class:`Embed`]
A list of embeds the message has.
channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`]
The :class:`TextChannel` or :class:`Thread` that the message was sent from.
Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message.
reference: Optional[:class:`~nextcord.MessageReference`]
The message that this message references. This is only applicable to messages of
type :attr:`MessageType.pins_add`, crossposted messages created by a
followed channel integration, or message replies.
.. versionadded:: 1.5
mention_everyone: :class:`bool`
Specifies if the message mentions everyone.
.. note::
This does not check if the ``@everyone`` or the ``@here`` text is in the message itself.
Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message
**and** it did end up mentioning.
mentions: List[:class:`abc.User`]
A list of :class:`Member` that were mentioned. If the message is in a private message
then the list will be of :class:`User` instead. For messages that are not of type
:attr:`MessageType.default`\, this array can be used to aid in system messages.
For more information, see :attr:`system_content`.
.. warning::
The order of the mentions list is not in any particular order so you should
not rely on it. This is a Discord limitation, not one with the library.
channel_mentions: List[:class:`abc.GuildChannel`]
A list of :class:`abc.GuildChannel` that were mentioned. If the message is in a private message
then the list is always empty.
role_mentions: List[:class:`Role`]
A list of :class:`Role` that were mentioned. If the message is in a private message
then the list is always empty.
id: :class:`int`
The message ID.
webhook_id: Optional[:class:`int`]
If this message was sent by a webhook, then this is the webhook ID's that sent this
message.
attachments: List[:class:`Attachment`]
A list of attachments given to a message.
pinned: :class:`bool`
Specifies if the message is currently pinned.
flags: :class:`MessageFlags`
Extra features of the message.
.. versionadded:: 1.3
reactions : List[:class:`Reaction`]
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
activity: Optional[:class:`dict`]
The activity associated with this message. Sent with Rich-Presence related messages that for
example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
- ``type``: An integer denoting the type of message activity being requested.
- ``party_id``: The party ID associated with the party.
application: Optional[:class:`dict`]
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
- ``id``: A string representing the application's ID.
- ``name``: A string representing the application's name.
- ``description``: A string representing the application's description.
- ``icon``: A string representing the icon ID of the application.
- ``cover_image``: A string representing the embed's image asset ID.
stickers: List[:class:`StickerItem`]
A list of sticker items given to the message.
.. versionadded:: 1.6
components: List[:class:`Component`]
A list of components in the message.
.. versionadded:: 2.0
guild: Optional[:class:`Guild`]
The guild that the message belongs to, if applicable.
interaction: Optional[:class:`MessageInteraction`]
The interaction data of a message, if applicable.
"""
__slots__ = (
"_state",
"_edited_timestamp",
"_cs_channel_mentions",
"_cs_raw_mentions",
"_cs_clean_content",
"_cs_raw_channel_mentions",
"_cs_raw_role_mentions",
"_cs_system_content",
"tts",
"content",
"channel",
"webhook_id",
"mention_everyone",
"embeds",
"id",
"interaction",
"mentions",
"author",
"attachments",
"nonce",
"pinned",
"role_mentions",
"type",
"flags",
"reactions",
"reference",
"application",
"activity",
"stickers",
"components",
"_background_tasks",
"guild",
)
if TYPE_CHECKING:
_HANDLERS: ClassVar[List[Tuple[str, Callable[..., None]]]]
_CACHED_SLOTS: ClassVar[List[str]]
guild: Optional[Guild]
reference: Optional[MessageReference]
mentions: List[Union[User, Member]]
author: Union[User, Member]
role_mentions: List[Role]
def __init__(
self,
*,
state: ConnectionState,
channel: MessageableChannel,
data: MessagePayload,
) -> None:
self._state: ConnectionState = state
self.id: int = int(data["id"])
self.webhook_id: Optional[int] = utils.get_as_snowflake(data, "webhook_id")
self.reactions: List[Reaction] = [
Reaction(message=self, data=d) for d in data.get("reactions", [])
]
self.attachments: List[Attachment] = [
Attachment(data=a, state=self._state) for a in data["attachments"]
]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data["embeds"]]
self.application: Optional[MessageApplicationPayload] = data.get("application")
self.activity: Optional[MessageActivityPayload] = data.get("activity")
self.channel: MessageableChannel = channel
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(
data["edited_timestamp"]
)
self.type: MessageType = try_enum(MessageType, data["type"])
self.pinned: bool = data["pinned"]
self.flags: MessageFlags = MessageFlags._from_value(data.get("flags", 0))
self.mention_everyone: bool = data["mention_everyone"]
self.tts: bool = data["tts"]
self.content: str = data["content"]
self.nonce: Optional[Union[int, str]] = data.get("nonce")
self.stickers: List[StickerItem] = [
StickerItem(data=d, state=state) for d in data.get("sticker_items", [])
]
self.components: List[Component] = [
_component_factory(d) for d in data.get("components", [])
]
self._background_tasks: Set[asyncio.Task[None]] = set()
try:
# if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild # type: ignore
except AttributeError:
if getattr(channel, "type", None) not in (ChannelType.group, ChannelType.private):
self.guild = state._get_guild(utils.get_as_snowflake(data, "guild_id"))
else:
self.guild = None
if (
(thread_data := data.get("thread"))
and not self.thread
and isinstance(self.guild, Guild)
):
self.guild._store_thread(thread_data)
try:
ref = data["message_reference"]
except KeyError:
self.reference = None
else:
self.reference = ref = MessageReference.with_state(state, ref)
try:
resolved = data["referenced_message"]
except KeyError:
pass
else:
if resolved is None:
ref.resolved = DeletedReferencedMessage(ref)
else:
# Right now the channel IDs match but maybe in the future they won't.
if ref.channel_id == channel.id:
chan = channel
else:
chan, _ = state._get_guild_channel(resolved)
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore
for handler in ("author", "member", "mentions", "mention_roles"):
try:
getattr(self, f"_handle_{handler}")(data[handler])
except KeyError:
continue
self.interaction: Optional[MessageInteraction] = (
MessageInteraction(data=data["interaction"], guild=self.guild, state=self._state)
if "interaction" in data
else None
)
def __repr__(self) -> str:
name = self.__class__.__name__
return f"<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>"
def _try_patch(self, data, key, transform=None) -> None:
try:
value = data[key]
except KeyError:
pass
else:
if transform is None:
setattr(self, key, value)
else:
setattr(self, key, transform(value))
def _add_reaction(self, data, emoji: Emoji | PartialEmoji | str, user_id) -> Reaction:
finder: Callable[[Reaction], bool] = lambda r: r.emoji == emoji
reaction = utils.find(finder, self.reactions)
is_me = data["me"] = user_id == self._state.self_id
if reaction is None:
reaction = Reaction(message=self, data=data, emoji=emoji)
self.reactions.append(reaction)
else:
reaction.count += 1
if is_me:
reaction.me = is_me
return reaction
def _remove_reaction(
self, data: ReactionPayload, emoji: EmojiInputType, user_id: int
) -> Reaction:
reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)
if reaction is None:
# already removed?
raise ValueError("Emoji already removed?")
# if reaction isn't in the list, we crash. This means discord
# sent bad data, or we stored improperly
reaction.count -= 1
if user_id == self._state.self_id:
reaction.me = False
if reaction.count == 0:
# this raises ValueError if something went wrong as well.
self.reactions.remove(reaction)
return reaction
def _clear_emoji(self, emoji) -> Optional[Reaction]:
to_check = str(emoji)
for index, reaction in enumerate(self.reactions): # noqa: B007
if str(reaction.emoji) == to_check:
break
else:
# didn't find anything so just return
return None
del self.reactions[index]
return reaction
def _update(self, data) -> None:
# In an update scheme, 'author' key has to be handled before 'member'
# otherwise they overwrite each other which is undesirable.
# Since there's no good way to do this we have to iterate over every
# handler rather than iterating over the keys which is a little slower
for key, handler in self._HANDLERS:
try:
value = data[key]
except KeyError:
continue
else:
handler(self, value)
# clear the cached properties
for attr in self._CACHED_SLOTS:
with contextlib.suppress(AttributeError):
delattr(self, attr)
def _handle_edited_timestamp(self, value: str) -> None:
self._edited_timestamp = utils.parse_time(value)
def _handle_pinned(self, value: bool) -> None:
self.pinned = value
def _handle_flags(self, value: int) -> None:
self.flags = MessageFlags._from_value(value)
def _handle_application(self, value: MessageApplicationPayload) -> None:
self.application = value
def _handle_activity(self, value: MessageActivityPayload) -> None:
self.activity = value
def _handle_mention_everyone(self, value: bool) -> None:
self.mention_everyone = value
def _handle_tts(self, value: bool) -> None:
self.tts = value
def _handle_type(self, value: int) -> None:
self.type = try_enum(MessageType, value)
def _handle_content(self, value: str) -> None:
self.content = value
def _handle_attachments(self, value: List[AttachmentPayload]) -> None:
self.attachments = [Attachment(data=a, state=self._state) for a in value]
def _handle_embeds(self, value: List[EmbedPayload]) -> None:
self.embeds = [Embed.from_dict(data) for data in value]
def _handle_nonce(self, value: Union[str, int]) -> None:
self.nonce = value
def _handle_author(self, author: UserPayload) -> None:
self.author = self._state.store_user(author)
if isinstance(self.guild, Guild):
found = self.guild.get_member(self.author.id)
if found is not None:
self.author = found
def _handle_member(self, member: MemberPayload) -> None:
# The gateway now gives us full Member objects sometimes with the following keys
# deaf, mute, joined_at, roles
# For the sake of performance I'm going to assume that the only
# field that needs *updating* would be the joined_at field.
# If there is no Member object (for some strange reason), then we can upgrade
# ourselves to a more "partial" member object.
author = self.author
try:
# Update member reference
author._update_from_message(member) # type: ignore
except AttributeError:
# It's a user here
# TODO: consider adding to cache here
self.author = Member._from_message(message=self, data=member)
def _handle_mentions(self, mentions: List[UserWithMemberPayload]) -> None:
self.mentions = r = []
guild = self.guild
state = self._state
if not isinstance(guild, Guild):
self.mentions = [state.store_user(m) for m in mentions]
return
for mention in filter(None, mentions):
id_search = int(mention["id"])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
else:
r.append(Member._try_upgrade(data=mention, guild=guild, state=state))
def _handle_mention_roles(self, role_mentions: List[int]) -> None:
self.role_mentions = []
if isinstance(self.guild, Guild):
for role_id in map(int, role_mentions):
role = self.guild.get_role(role_id)
if role is not None:
self.role_mentions.append(role)
def _handle_components(self, components: List[ComponentPayload]) -> None:
self.components = [_component_factory(d) for d in components]
def _handle_thread(self, thread: Optional[ThreadPayload]) -> None:
if thread:
self.guild._store_thread(thread) # type: ignore
def _rebind_cached_references(
self, new_guild: Guild, new_channel: Union[TextChannel, Thread]
) -> None:
self.guild = new_guild
self.channel = new_channel
def raw_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of user IDs matched with
the syntax of ``<@user_id>`` in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return utils.parse_raw_mentions(self.content)
def raw_channel_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of channel IDs matched with
the syntax of ``<#channel_id>`` in the message content.
"""
return utils.parse_raw_channel_mentions(self.content)
def raw_role_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of role IDs matched with
the syntax of ``<@&role_id>`` in the message content.
"""
return utils.parse_raw_role_mentions(self.content)
def channel_mentions(self) -> List[GuildChannel]:
if self.guild is None:
return []
it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions))
return utils.unique(it)
def clean_content(self) -> str:
""":class:`str`: A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* affect markdown. If you want to escape
or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown`
respectively, along with this function.
"""
transformations = {
re.escape(f"<#{channel.id}>"): "#" + channel.name for channel in self.channel_mentions
}
mention_transforms = {
re.escape(f"<@{member.id}>"): "@" + member.display_name for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape(f"<@!{member.id}>"): "@" + member.display_name for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape(f"<@&{role.id}>"): "@" + role.name for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), "")
pattern = re.compile("|".join(transformations.keys()))
result = pattern.sub(repl, self.content)
return escape_mentions(result)
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The message's creation time in UTC."""
return utils.snowflake_time(self.id)
def edited_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: An aware UTC datetime object containing the edited time of the message."""
return self._edited_timestamp
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this message."""
guild_id = getattr(self.guild, "id", "@me")
return f"https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}"
def thread(self) -> Optional[Thread]:
"""Optional[:class:`Thread`]: The thread started from this message. None if no thread was started."""
if not isinstance(self.guild, Guild):
return None
return self.guild.get_thread(self.id)
def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API
in response to something.
.. versionadded:: 1.3
"""
return self.type not in (
MessageType.default,
MessageType.reply,
MessageType.chat_input_command,
MessageType.context_menu_command,
MessageType.thread_starter_message,
)
def system_content(self):
r""":class:`str`: A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default` and :attr:`MessageType.reply`\,
this just returns the regular :attr:`Message.content`. Otherwise this
returns an English message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.recipient_add:
if self.channel.type is ChannelType.group:
return f"{self.author.name} added {self.mentions[0].name} to the group."
return f"{self.author.name} added {self.mentions[0].name} to the thread."
if self.type is MessageType.recipient_remove:
if self.channel.type is ChannelType.group:
return f"{self.author.name} removed {self.mentions[0].name} from the group."
return f"{self.author.name} removed {self.mentions[0].name} from the thread."
if self.type is MessageType.channel_name_change:
return f"{self.author.name} changed the channel name: **{self.content}**"
if self.type is MessageType.channel_icon_change:
return f"{self.author.name} changed the channel icon."
if self.type is MessageType.pins_add:
return f"{self.author.name} pinned a message to this channel."
if self.type is MessageType.new_member:
formats = [
"{0} joined the party.",
"{0} is here.",
"Welcome, {0}. We hope you brought pizza.",
"A wild {0} appeared.",
"{0} just landed.",
"{0} just slid into the server.",
"{0} just showed up!",
"Welcome {0}. Say hi!",
"{0} hopped into the server.",
"Everyone welcome {0}!",
"Glad you're here, {0}.",
"Good to see you, {0}.",
"Yay you made it, {0}!",
]
created_at_ms = int(self.created_at.timestamp() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.premium_guild_subscription:
if not self.content:
return f"{self.author.name} just boosted the server!"
return f"{self.author.name} just boosted the server **{self.content}** times!"
if self.type is MessageType.premium_guild_tier_1:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**"
if self.type is MessageType.premium_guild_tier_2:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**"
if self.type is MessageType.premium_guild_tier_3:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**"
if self.type is MessageType.channel_follow_add:
return f"{self.author.name} has added {self.content} to this channel"
if self.type is MessageType.guild_stream:
# the author will be a Member
return f"{self.author.name} is live! Now streaming {self.author.activity.name}" # type: ignore
if self.type is MessageType.guild_discovery_disqualified:
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details."
if self.type is MessageType.guild_discovery_requalified:
return "This server is eligible for Server Discovery again and has been automatically relisted!"
if self.type is MessageType.guild_discovery_grace_period_initial_warning:
return "This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery."
if self.type is MessageType.guild_discovery_grace_period_final_warning:
return "This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery."
if self.type is MessageType.thread_created:
return f"{self.author.name} started a thread: **{self.content}**. See all **threads**."
if self.type is MessageType.reply:
return self.content
if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None:
return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore
if self.type is MessageType.guild_invite_reminder:
return "Wondering who to invite?\nStart by inviting anyone who can help you build the server!"
if self.type is MessageType.stage_start:
return f"{self.author.display_name} started {self.content}"
if self.type is MessageType.stage_end:
return f"{self.author.display_name} ended {self.content}"
if self.type is MessageType.stage_speaker:
return f"{self.author.display_name} is now a speaker."
if self.type is MessageType.stage_topic:
return f"{self.author.display_name} changed the Stage topic: {self.content}"
return None
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1
Added the new ``delay`` keyword-only parameter.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message. If the deletion fails then it is silently ignored.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
NotFound
The message was deleted already
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete(delay: float) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await self._state.http.delete_message(self.channel.id, self.id)
task = asyncio.create_task(delete(delay))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await self._state.http.delete_message(self.channel.id, self.id)
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
content: Optional[str] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: List[Embed] = MISSING,
attachments: List[Attachment] = MISSING,
suppress: bool = MISSING,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
view: Optional[View] = MISSING,
file: Optional[File] = MISSING,
files: Optional[List[File]] = MISSING,
) -> Message:
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
.. versionchanged:: 1.3
The ``suppress`` keyword-only parameter was added.
Parameters
----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
embeds: List[:class:`Embed`]
The new embeds to replace the original with. Must be a maximum of 10.
To remove all embeds ``[]`` should be passed.
.. versionadded:: 2.0
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep all existing attachments,
pass ``message.attachments``.
suppress: :class:`bool`
Whether to suppress embeds for the message. This removes
all the embeds if set to ``True``. If set to ``False``
this brings the embeds back if they were suppressed.
Using this parameter requires :attr:`~.Permissions.manage_messages`.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~nextcord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~nextcord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~nextcord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~nextcord.Client.allowed_mentions`
are used instead.
.. versionadded:: 1.4
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
file: Optional[:class:`File`]
If provided, a new file to add to the message.
.. versionadded:: 2.0
files: Optional[List[:class:`File`]]
If provided, a list of new files to add to the message.
.. versionadded:: 2.0
Raises
------
HTTPException
Editing the message failed.
Forbidden
Tried to suppress a message without permissions or
edited a message's content or embed that isn't yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
Returns
-------
:class:`Message`
The edited message.
"""
payload: Dict[str, Any] = {}
if content is not MISSING:
if content is not None:
payload["content"] = str(content)
else:
payload["content"] = None
if embed is not MISSING and embeds is not MISSING:
raise InvalidArgument("Cannot pass both embed and embeds parameter to edit()")
if file is not MISSING and files is not MISSING:
raise InvalidArgument("Cannot pass both file and files parameter to edit()")
if embed is not MISSING:
if embed is None:
payload["embeds"] = []
else:
payload["embeds"] = [embed.to_dict()]
elif embeds is not MISSING:
payload["embeds"] = [e.to_dict() for e in embeds]
if suppress is not MISSING:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = suppress
payload["flags"] = flags.value
if allowed_mentions is MISSING:
if self._state.allowed_mentions is not None and self.author.id == self._state.self_id:
payload["allowed_mentions"] = self._state.allowed_mentions.to_dict()
elif allowed_mentions is not None:
if self._state.allowed_mentions is not None:
payload["allowed_mentions"] = self._state.allowed_mentions.merge(
allowed_mentions
).to_dict()
else:
payload["allowed_mentions"] = allowed_mentions.to_dict()
if attachments is not MISSING:
payload["attachments"] = [a.to_dict() for a in attachments]
if view is not MISSING:
self._state.prevent_view_updates_for(self.id)
if view:
payload["components"] = view.to_components()
else:
payload["components"] = []
if file is not MISSING:
payload["files"] = [file]
elif files is not MISSING:
payload["files"] = files
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
message = Message(state=self._state, channel=self.channel, data=data)
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, self.id)
if delete_after is not None:
await self.delete(delay=delete_after)
return message
async def publish(self) -> None:
"""|coro|
Publishes this message to your announcement channel.
You must have the :attr:`~Permissions.send_messages` permission to do this.
If the message is not your own then the :attr:`~Permissions.manage_messages`
permission is also needed.
Raises
------
Forbidden
You do not have the proper permissions to publish this message.
HTTPException
Publishing the message failed.
"""
await self._state.http.publish_message(self.channel.id, self.id)
async def pin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for pinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id, reason=reason)
self.pinned = True
async def unpin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for unpinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id, reason=reason)
self.pinned = False
async def add_reaction(self, emoji: EmojiInputType) -> None:
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
async def remove_reaction(
self, emoji: Union[EmojiInputType, Reaction], member: Snowflake
) -> None:
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:
"""|coro|
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You need the :attr:`~Permissions.manage_messages` permission to use this.
.. versionadded:: 1.3
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to clear.
Raises
------
HTTPException
Clearing the reaction failed.
Forbidden
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji)
async def clear_reactions(self) -> None:
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
async def create_thread(
self, *, name: str, auto_archive_duration: ThreadArchiveDuration = MISSING
) -> Thread:
"""|coro|
Creates a public thread from this message.
You must have :attr:`~nextcord.Permissions.create_public_threads` in order to
create a public thread from a message.
The channel this message belongs in must be a :class:`TextChannel`.
.. versionadded:: 2.0
Parameters
----------
name: :class:`str`
The name of the thread.
auto_archive_duration: :class:`int`
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
Raises
------
Forbidden
You do not have permissions to create a thread.
HTTPException
Creating the thread failed.
InvalidArgument
This message does not have guild info attached.
Returns
-------
:class:`.Thread`
The created thread.
"""
if self.guild is None:
raise InvalidArgument("This message does not have guild info attached.")
default_auto_archive_duration: ThreadArchiveDuration = getattr(
self.channel, "default_auto_archive_duration", 1440
)
data = await self._state.http.start_thread_with_message(
self.channel.id,
self.id,
name=name,
auto_archive_duration=auto_archive_duration or default_auto_archive_duration,
)
return Thread(guild=self.guild, state=self._state, data=data)
async def reply(self, content: Optional[str] = None, **kwargs) -> Message:
"""|coro|
A shortcut method to :meth:`.abc.Messageable.send` to reply to the
:class:`.Message`.
.. versionadded:: 1.6
Raises
------
~nextcord.HTTPException
Sending the message failed.
~nextcord.Forbidden
You do not have the proper permissions to send the message.
~nextcord.InvalidArgument
The ``files`` list is not of the appropriate size or
you specified both ``file`` and ``files``.
Returns
-------
:class:`.Message`
The message that was sent.
"""
return await self.channel.send(content, reference=self, **kwargs)
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a :class:`~nextcord.MessageReference` from the current message.
.. versionadded:: 1.6
Parameters
----------
fail_if_not_exists: :class:`bool`
Whether replying using the message reference should raise :class:`HTTPException`
if the message no longer exists or Discord could not fetch the message.
.. versionadded:: 1.7
Returns
-------
:class:`~nextcord.MessageReference`
The reference to this message.
"""
return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists)
def to_message_reference_dict(self) -> MessageReferencePayload:
data: MessageReferencePayload = {
"message_id": self.id,
"channel_id": self.channel.id,
}
if self.guild is not None:
data["guild_id"] = self.guild.id
return data
CoroFunc = Callable[..., Coro[Any]]
The provided code snippet includes necessary dependencies for implementing the `dynamic_cooldown` function. Write a Python function `def dynamic_cooldown( cooldown: Union[BucketType, Callable[[Message], Any]], type: BucketType = BucketType.default ) -> Callable[[T], T]` to solve the following problem:
A decorator that adds a dynamic cooldown to a :class:`.Command` This differs from :func:`.cooldown` in that it takes a function that accepts a single parameter of type :class:`.nextcord.Message` and must return a :class:`.Cooldown` or ``None``. If ``None`` is returned then that cooldown is effectively bypassed. A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. .. versionadded:: 2.0 Parameters ---------- cooldown: Callable[[:class:`.nextcord.Message`], Optional[:class:`.Cooldown`]] A function that takes a message and returns a cooldown that will apply to this invocation or ``None`` if the cooldown should be bypassed. type: :class:`.BucketType` The type of cooldown to have.
Here is the function:
def dynamic_cooldown(
cooldown: Union[BucketType, Callable[[Message], Any]], type: BucketType = BucketType.default
) -> Callable[[T], T]:
"""A decorator that adds a dynamic cooldown to a :class:`.Command`
This differs from :func:`.cooldown` in that it takes a function that
accepts a single parameter of type :class:`.nextcord.Message` and must
return a :class:`.Cooldown` or ``None``. If ``None`` is returned then
that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount
of times in a specific time frame. These cooldowns can be based
either on a per-guild, per-channel, per-user, per-role or global basis.
Denoted by the third argument of ``type`` which must be of enum
type :class:`.BucketType`.
If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in
:func:`.on_command_error` and the local error handler.
A command can only have a single cooldown.
.. versionadded:: 2.0
Parameters
----------
cooldown: Callable[[:class:`.nextcord.Message`], Optional[:class:`.Cooldown`]]
A function that takes a message and returns a cooldown that will
apply to this invocation or ``None`` if the cooldown should be bypassed.
type: :class:`.BucketType`
The type of cooldown to have.
"""
if not callable(cooldown):
raise TypeError("A callable must be provided")
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func._buckets = DynamicCooldownMapping(cooldown, type)
else:
func.__commands_cooldown__ = DynamicCooldownMapping(cooldown, type)
return func
return decorator # type: ignore | A decorator that adds a dynamic cooldown to a :class:`.Command` This differs from :func:`.cooldown` in that it takes a function that accepts a single parameter of type :class:`.nextcord.Message` and must return a :class:`.Cooldown` or ``None``. If ``None`` is returned then that cooldown is effectively bypassed. A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of ``type`` which must be of enum type :class:`.BucketType`. If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in :func:`.on_command_error` and the local error handler. A command can only have a single cooldown. .. versionadded:: 2.0 Parameters ---------- cooldown: Callable[[:class:`.nextcord.Message`], Optional[:class:`.Cooldown`]] A function that takes a message and returns a cooldown that will apply to this invocation or ``None`` if the cooldown should be bypassed. type: :class:`.BucketType` The type of cooldown to have. |
160,906 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
class Command(_BaseCommand, Generic[CogT, P, T]):
r"""A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The coroutine that is executed when the command is called.
help: Optional[:class:`str`]
The long help text for the command.
brief: Optional[:class:`str`]
The short help text for the command.
usage: Optional[:class:`str`]
A replacement for arguments in the default help text.
aliases: Union[List[:class:`str`], Tuple[:class:`str`]]
The list of aliases the command can be invoked under.
enabled: :class:`bool`
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
:exc:`.DisabledCommand` is raised to the :func:`.on_command_error`
event. Defaults to ``True``.
parent: Optional[:class:`Group`]
The parent group that this command belongs to. ``None`` if there
isn't one.
cog: Optional[:class:`Cog`]
The cog that this command belongs to. ``None`` if there isn't one.
checks: List[Callable[[:class:`.Context`], :class:`bool`]]
A list of predicates that verifies if the command could be executed
with the given :class:`.Context` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.CommandError` should be used. Note that if the checks fail then
:exc:`.CheckFailure` exception is raised to the :func:`.on_command_error`
event.
description: :class:`str`
The message prefixed into the default help command.
hidden: :class:`bool`
If ``True``\, the default help command does not show this in the
help output.
rest_is_raw: :class:`bool`
If ``False`` and a keyword-only argument is provided then the keyword
only argument is stripped and handled as if it was a regular argument
that handles :exc:`.MissingRequiredArgument` and default values in a
regular matter rather than passing the rest completely raw. If ``True``
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults to ``False``.
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked, if any.
require_var_positional: :class:`bool`
If ``True`` and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults to ``False``.
.. versionadded:: 1.5
ignore_extra: :class:`bool`
If ``True``\, ignores extraneous strings passed to a command if all its
requirements are met (e.g. ``?foo a b c`` when only expecting ``a``
and ``b``). Otherwise :func:`.on_command_error` and local error handlers
are called with :exc:`.TooManyArguments`. Defaults to ``True``.
cooldown_after_parsing: :class:`bool`
If ``True``\, cooldown processing is done after argument parsing,
which calls converters. If ``False`` then cooldown processing is done
first and then the converters are called second. Defaults to ``False``.
extras: :class:`dict`
A dict of user provided extras to attach to the Command.
.. note::
This object may be copied by the library.
.. versionadded:: 2.0
inherit_hooks: :class:`bool`
If ``True`` and this command has a parent :class:`Group` then this command
will inherit all checks, pre_invoke and after_invoke's defined on the the :class:`Group`
This defaults to ``False``
.. note::
Any ``pre_invoke`` or ``after_invoke``'s defined on this will override parent ones.
.. versionadded:: 2.0.0
"""
__original_kwargs__: Dict[str, Any]
def __new__(cls, *_args: Any, **kwargs: Any) -> Self:
# if you're wondering why this is done, it's because we need to ensure
# we have a complete original copy of **kwargs even for classes that
# mess with it by popping before delegating to the subclass __init__.
# In order to do this, we need to control the instance creation and
# inject the original kwargs through __new__ rather than doing it
# inside __init__.
self = super().__new__(cls)
# we do a shallow copy because it's probably the most common use case.
# this could potentially break if someone modifies a list or something
# while it's in movement, but for now this is the cheapest and
# fastest way to do what we want.
self.__original_kwargs__ = kwargs.copy()
return self
def __init__(
self,
func: Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
],
**kwargs: Any,
) -> None:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine.")
name = kwargs.get("name") or func.__name__
if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
self.name: str = name
# ContextT is incompatible with normal Context
self.callback = func # pyright: ignore
self.enabled: bool = kwargs.get("enabled", True)
help_doc = kwargs.get("help")
if help_doc is not None:
help_doc = inspect.cleandoc(help_doc)
else:
help_doc = inspect.getdoc(func)
if isinstance(help_doc, bytes):
help_doc = help_doc.decode("utf-8")
self.help: Optional[str] = help_doc
self.brief: Optional[str] = kwargs.get("brief")
self.usage: Optional[str] = kwargs.get("usage")
self.rest_is_raw: bool = kwargs.get("rest_is_raw", False)
self.aliases: Union[List[str], Tuple[str]] = kwargs.get("aliases", [])
self.extras: Dict[str, Any] = kwargs.get("extras", {})
if not isinstance(self.aliases, (list, tuple)):
raise TypeError("Aliases of a command must be a list or a tuple of strings.")
self.description: str = inspect.cleandoc(kwargs.get("description", ""))
self.hidden: bool = kwargs.get("hidden", False)
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks: List[Check] = checks
try:
cooldown = func.__commands_cooldown__
except AttributeError:
cooldown = kwargs.get("cooldown")
if cooldown is None:
buckets = CooldownMapping(cooldown, BucketType.default)
elif isinstance(cooldown, CooldownMapping):
buckets = cooldown
else:
raise TypeError("Cooldown must be an instance of CooldownMapping or None.")
self._buckets: CooldownMapping = buckets
try:
max_concurrency = func.__commands_max_concurrency__
except AttributeError:
max_concurrency = kwargs.get("max_concurrency")
self._max_concurrency: Optional[MaxConcurrency] = max_concurrency
self.require_var_positional: bool = kwargs.get("require_var_positional", False)
self.ignore_extra: bool = kwargs.get("ignore_extra", True)
self.cooldown_after_parsing: bool = kwargs.get("cooldown_after_parsing", False)
self.cog: Optional[CogT] = None
# bandaid for the fact that sometimes parent can be the bot instance
parent = kwargs.get("parent")
self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore
self._before_invoke: Optional[Hook] = None
try:
before_invoke = func.__before_invoke__
except AttributeError:
pass
else:
self.before_invoke(before_invoke)
self._after_invoke: Optional[Hook] = None
try:
after_invoke = func.__after_invoke__
except AttributeError:
pass
else:
self.after_invoke(after_invoke)
# Attempt to bind to parent hooks if applicable
if not kwargs.get("inherit_hooks", False):
return
# We should be binding hooks
if not self.parent:
return
inherited_before_invoke: Optional[Hook] = None
try:
inherited_before_invoke = self.parent._before_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_before_invoke:
self.before_invoke(inherited_before_invoke)
inherited_after_invoke: Optional[Hook] = None
try:
inherited_after_invoke = self.parent._after_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_after_invoke:
self.after_invoke(inherited_after_invoke)
self.checks.extend(self.parent.checks) # type: ignore
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_guild_permissions", {})
def callback(
self,
) -> Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]:
return self._callback
def callback(
self,
function: Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
],
) -> None:
self._callback = function
unwrap = unwrap_function(function)
self.module = unwrap.__module__
try:
globalns = unwrap.__globals__
except AttributeError:
globalns = {}
self.params = get_signature_parameters(function, globalns)
def add_check(self, func: Check) -> None:
"""Adds a check to the command.
This is the non-decorator interface to :func:`.check`.
.. versionadded:: 1.3
Parameters
----------
func
The function that will be used as a check.
"""
self.checks.append(func)
def remove_check(self, func: Check) -> None:
"""Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command's checks.
.. versionadded:: 1.3
Parameters
----------
func
The function to remove from the checks.
"""
with contextlib.suppress(ValueError):
self.checks.remove(func)
def update(self, **kwargs: Any) -> None:
"""Updates :class:`Command` instance with updated attribute.
This works similarly to the :func:`.command` decorator in terms
of parameters in that they are passed to the :class:`Command` or
subclass constructors, sans the name and callback.
"""
self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs))
async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T:
"""|coro|
Calls the internal callback that the command holds.
.. note::
This bypasses all mechanisms -- including checks, converters,
invoke hooks, cooldowns, etc. You must take care to pass
the proper arguments and types to this function.
.. versionadded:: 1.3
"""
if self.cog is not None:
return await self.callback(self.cog, context, *args, **kwargs) # type: ignore
return await self.callback(context, *args, **kwargs) # type: ignore
def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT:
other._before_invoke = self._before_invoke
other._after_invoke = self._after_invoke
if self.checks != other.checks:
other.checks = self.checks.copy()
if self._buckets.valid and not other._buckets.valid:
other._buckets = self._buckets.copy()
if self._max_concurrency != other._max_concurrency:
# _max_concurrency won't be None at this point
other._max_concurrency = self._max_concurrency.copy() # type: ignore
with contextlib.suppress(AttributeError):
other.on_error = self.on_error
return other
def copy(self) -> Self:
"""Creates a copy of this command.
Returns
-------
:class:`Command`
A new instance of this command.
"""
ret = self.__class__(self.callback, **self.__original_kwargs__)
return self._ensure_assignment_on_copy(ret)
def _update_copy(self, kwargs: Dict[str, Any]) -> Self:
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = self.__class__(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
return self.copy()
async def dispatch_error(self, ctx: Context, error: Exception) -> None:
ctx.command_failed = True
cog = self.cog
try:
coro = self.on_error
except AttributeError:
pass
else:
injected = wrap_callback(coro)
if cog is not None:
await injected(cog, ctx, error)
else:
await injected(ctx, error)
try:
if cog is not None:
local = Cog._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch("command_error", ctx, error)
async def transform(self, ctx: Context, param: inspect.Parameter) -> Any:
required = param.default is param.empty
converter = get_converter(param)
consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw
view = ctx.view
view.skip_ws()
# The greedy converter is simple -- it keeps going until it fails in which case,
# it undos the view ready for the next parameter to use instead
if isinstance(converter, Greedy):
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
return await self._transform_greedy_pos(ctx, param, required, converter.converter)
if param.kind == param.VAR_POSITIONAL:
return await self._transform_greedy_var_pos(ctx, param, converter.converter)
# if we're here, then it's a KEYWORD_ONLY param type
# since this is mostly useless, we'll helpfully transform Greedy[X]
# into just X and do the parsing that way.
converter = converter.converter
if view.eof:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError # break the loop
if required:
if self._is_typing_optional(param.annotation):
return None
if hasattr(converter, "__commands_is_flag__") and converter._can_be_constructible():
return await converter._construct_default(ctx)
raise MissingRequiredArgument(param)
return param.default
previous = view.index
if consume_rest_is_special:
argument = view.read_rest().strip()
else:
try:
argument = view.get_quoted_word()
except ArgumentParsingError:
if self._is_typing_optional(param.annotation):
view.index = previous
return None
raise
view.previous = previous
if argument is None:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError
if required:
if self._is_typing_optional(param.annotation):
return None
raise MissingRequiredArgument(param)
return param.default
# type-checker fails to narrow argument
return await run_converters(ctx, converter, argument, param)
async def _transform_greedy_pos(
self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any
) -> Any:
view = ctx.view
result = []
while not view.eof:
# for use with a manual undo
previous = view.index
view.skip_ws()
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
break
else:
result.append(value)
if not result and not required:
return param.default
return result
async def _transform_greedy_var_pos(
self, ctx: Context, param: inspect.Parameter, converter: Any
) -> Any:
view = ctx.view
previous = view.index
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
raise RuntimeError from None # break loop
else:
return value
def clean_params(self) -> Dict[str, inspect.Parameter]:
"""Dict[:class:`str`, :class:`inspect.Parameter`]:
Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'self' parameter") from None
try:
# first/second parameter is context
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'context' parameter") from None
return result
def full_parent_name(self) -> str:
""":class:`str`: Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``.
"""
entries = []
command = self
# command.parent is type-hinted as GroupMixin some attributes are resolved via MRO
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command.name) # type: ignore
return " ".join(reversed(entries))
def parents(self) -> List[Group]:
"""List[:class:`Group`]: Retrieves the parents of this command.
If the command has no parents then it returns an empty :class:`list`.
For example in commands ``?a b c test``, the parents are ``[c, b, a]``.
.. versionadded:: 1.1
"""
entries = []
command = self
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command)
return entries
def root_parent(self) -> Optional[Group]:
"""Optional[:class:`Group`]: Retrieves the root parent of this command.
If the command has no parents then it returns ``None``.
For example in commands ``?a b c test``, the root parent is ``a``.
"""
if not self.parent:
return None
return self.parents[-1]
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return parent + " " + self.name
return self.name
def __str__(self) -> str:
return self.qualified_name
async def _parse_arguments(self, ctx: Context) -> None:
ctx.args = [ctx] if self.cog is None else [self.cog, ctx]
ctx.kwargs = {}
args = ctx.args
kwargs = ctx.kwargs
view = ctx.view
iterator = iter(self.params.items())
if self.cog is not None:
# we have 'self' as the first parameter so just advance
# the iterator and resume parsing
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "self" parameter.'
) from None
# next we have the 'ctx' as the next parameter
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "ctx" parameter.'
) from None
for name, param in iterator:
ctx.current_parameter = param
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
transformed = await self.transform(ctx, param)
args.append(transformed)
elif param.kind == param.KEYWORD_ONLY:
# kwarg only param denotes "consume rest" semantics
if self.rest_is_raw:
converter = get_converter(param)
argument = view.read_rest()
kwargs[name] = await run_converters(ctx, converter, argument, param)
else:
kwargs[name] = await self.transform(ctx, param)
break
elif param.kind == param.VAR_POSITIONAL:
if view.eof and self.require_var_positional:
raise MissingRequiredArgument(param)
while not view.eof:
try:
transformed = await self.transform(ctx, param)
args.append(transformed)
except RuntimeError:
break
if not self.ignore_extra and not view.eof:
raise TooManyArguments("Too many arguments passed to " + self.qualified_name)
async def call_before_hooks(self, ctx: Context) -> None:
# now that we're done preparing we can call the pre-command hooks
# first, call the command local hook:
cog = self.cog
if self._before_invoke is not None:
# should be cog if @commands.before_invoke is used
instance = getattr(self._before_invoke, "__self__", cog)
# __self__ only exists for methods, not functions
# however, if @command.before_invoke is used, it will be a function
if instance:
await self._before_invoke(instance, ctx) # type: ignore
else:
await self._before_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_before_invoke)
if hook is not None:
await hook(ctx)
# call the bot global hook if necessary
hook = ctx.bot._before_invoke
if hook is not None:
await hook(ctx)
async def call_after_hooks(self, ctx: Context) -> None:
cog = self.cog
if self._after_invoke is not None:
instance = getattr(self._after_invoke, "__self__", cog)
if instance:
await self._after_invoke(instance, ctx) # type: ignore
else:
await self._after_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
def _prepare_cooldowns(self, ctx: Context) -> None:
if self._buckets.valid:
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
bucket = self._buckets.get_bucket(ctx.message, current)
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
async def prepare(self, ctx: Context) -> None:
ctx.command = self
if not await self.can_run(ctx):
raise CheckFailure(f"The check functions for command {self.qualified_name} failed.")
if self._max_concurrency is not None:
# For this application, context can be duck-typed as a Message
await self._max_concurrency.acquire(ctx) # type: ignore
try:
if self.cooldown_after_parsing:
await self._parse_arguments(ctx)
self._prepare_cooldowns(ctx)
else:
self._prepare_cooldowns(ctx)
await self._parse_arguments(ctx)
await self.call_before_hooks(ctx)
except:
if self._max_concurrency is not None:
await self._max_concurrency.release(ctx) # type: ignore
raise
def is_on_cooldown(self, ctx: Context) -> bool:
"""Checks whether the command is currently on cooldown.
Parameters
----------
ctx: :class:`.Context`
The invocation context to use when checking the commands cooldown status.
Returns
-------
:class:`bool`
A boolean indicating if the command is on cooldown.
"""
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_tokens(current) == 0
def reset_cooldown(self, ctx: Context) -> None:
"""Resets the cooldown on this command.
Parameters
----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.reset()
def get_cooldown_retry_after(self, ctx: Context) -> float:
"""Retrieves the amount of seconds before this command can be tried again.
.. versionadded:: 1.4
Parameters
----------
ctx: :class:`.Context`
The invocation context to retrieve the cooldown from.
Returns
-------
:class:`float`
The amount of time left on this command's cooldown in seconds.
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_retry_after(current)
return 0.0
async def invoke(self, ctx: Context) -> None:
await self.prepare(ctx)
# terminate the invoked_subcommand chain.
# since we're in a regular command (and not a group) then
# the invoked subcommand is None.
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
ctx.invoked_subcommand = None
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
def error(self, coro: ErrorT) -> ErrorT:
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The error handler must be a coroutine.")
self.on_error: Error = coro
return coro
def has_error_handler(self) -> bool:
""":class:`bool`: Checks whether the command has an error handler registered.
.. versionadded:: 1.7
"""
return hasattr(self, "on_error")
def before_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The pre-invoke hook must be a coroutine.")
self._before_invoke = coro
return coro
def after_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The post-invoke hook must be a coroutine.")
self._after_invoke = coro
return coro
def cog_name(self) -> Optional[str]:
"""Optional[:class:`str`]: The name of the cog this command belongs to, if any."""
return type(self.cog).__cog_name__ if self.cog is not None else None
def short_doc(self) -> str:
""":class:`str`: Gets the "short" documentation of a command.
By default, this is the :attr:`.brief` attribute.
If that lookup leads to an empty string then the first line of the
:attr:`.help` attribute is used instead.
"""
if self.brief is not None:
return self.brief
if self.help is not None:
return self.help.split("\n", 1)[0]
return ""
def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]:
return getattr(annotation, "__origin__", None) is Union and type(None) in annotation.__args__ # type: ignore
def signature(self) -> str:
""":class:`str`: Returns a POSIX-like signature useful for help command output."""
if self.usage is not None:
return self.usage
params = self.clean_params
if not params:
return ""
result = []
for name, param in params.items():
greedy = isinstance(param.annotation, Greedy)
optional = False # postpone evaluation of if it's an optional argument
# for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the
# parameter signature is a literal list of it's values
annotation = param.annotation.converter if greedy else param.annotation
origin = getattr(annotation, "__origin__", None)
if not greedy and origin is Union:
none_cls = type(None)
union_args = annotation.__args__
optional = union_args[-1] is none_cls
if len(union_args) == 2 and optional:
annotation = union_args[0]
origin = getattr(annotation, "__origin__", None)
if origin is Literal:
name = "|".join(
f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__
)
if param.default is not param.empty:
# We don't want None or '' to trigger the [name=value] case and instead it should
# do [name] since [name=None] or [name=] are not exactly useful for the user.
should_print = (
param.default if isinstance(param.default, str) else param.default is not None
)
if should_print:
result.append(
f"[{name}={param.default}]"
if not greedy
else f"[{name}={param.default}]..."
)
continue
result.append(f"[{name}]")
elif param.kind == param.VAR_POSITIONAL:
if self.require_var_positional:
result.append(f"<{name}...>")
else:
result.append(f"[{name}...]")
elif greedy:
result.append(f"[{name}]...")
elif optional:
result.append(f"[{name}]")
else:
result.append(f"<{name}>")
return " ".join(result)
async def can_run(self, ctx: Context) -> bool:
"""|coro|
Checks if the command can be executed by checking all the predicates
inside the :attr:`~Command.checks` attribute. This also checks whether the
command is disabled.
.. versionchanged:: 1.3
Checks whether the command is disabled or not
Parameters
----------
ctx: :class:`.Context`
The ctx of the command currently being invoked.
Raises
------
:class:`CommandError`
Any command error that was raised during a check call will be propagated
by this function.
Returns
-------
:class:`bool`
A boolean indicating if the command can be invoked.
"""
if not self.enabled:
raise DisabledCommand(f"{self.name} command is disabled")
original = ctx.command
ctx.command = self
try:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.qualified_name} failed."
)
cog = self.cog
if cog is not None:
local_check = Cog._get_overridden_method(cog.cog_check)
if local_check is not None:
ret = await nextcord.utils.maybe_coroutine(local_check, ctx)
if not ret:
return False
predicates = self.checks
if not predicates:
# since we have no checks, then we just return True.
return True
return await nextcord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
finally:
ctx.command = original
class BucketType(IntEnum):
default = 0
user = 1
guild = 2
channel = 3
member = 4
category = 5
role = 6
def get_key(self, msg: Message) -> Any:
if self is BucketType.user:
return msg.author.id
if self is BucketType.guild:
return (msg.guild or msg.author).id
if self is BucketType.channel:
return msg.channel.id
if self is BucketType.member:
return ((msg.guild and msg.guild.id), msg.author.id)
if self is BucketType.category:
return (msg.channel.category or msg.channel).id # type: ignore
if self is BucketType.role:
# we return the channel id of a private-channel as there are only roles in guilds
# and that yields the same result as for a guild with only the @everyone role
# NOTE: PrivateChannel doesn't actually have an id attribute but we assume we are
# recieving a DMChannel or GroupChannel which inherit from PrivateChannel and do
return (msg.channel if isinstance(msg.channel, PrivateChannel) else msg.author.top_role).id # type: ignore
return None
def __call__(self, msg: Message) -> Any:
return self.get_key(msg)
class MaxConcurrency:
__slots__ = ("number", "per", "wait", "_mapping")
def __init__(self, number: int, *, per: BucketType, wait: bool) -> None:
self._mapping: Dict[Any, _Semaphore] = {}
self.per: BucketType = per
self.number: int = number
self.wait: bool = wait
if number <= 0:
raise ValueError("max_concurrency 'number' cannot be less than 1")
if not isinstance(per, BucketType):
raise TypeError(f"max_concurrency 'per' must be of type BucketType not {type(per)!r}")
def copy(self) -> Self:
return self.__class__(self.number, per=self.per, wait=self.wait)
def __repr__(self) -> str:
return f"<MaxConcurrency per={self.per!r} number={self.number} wait={self.wait}>"
def get_key(self, message: Message) -> Any:
return self.per.get_key(message)
async def acquire(self, message: Message) -> None:
key = self.get_key(message)
try:
sem = self._mapping[key]
except KeyError:
self._mapping[key] = sem = _Semaphore(self.number)
acquired = await sem.acquire(wait=self.wait)
if not acquired:
raise MaxConcurrencyReached(self.number, self.per)
async def release(self, message: Message) -> None:
# Technically there's no reason for this function to be async
# But it might be more useful in the future
key = self.get_key(message)
try:
sem = self._mapping[key]
except KeyError:
# ...? peculiar
return
else:
sem.release()
if sem.value >= self.number and not sem.is_active():
del self._mapping[key]
CoroFunc = Callable[..., Coro[Any]]
The provided code snippet includes necessary dependencies for implementing the `max_concurrency` function. Write a Python function `def max_concurrency( number: int, per: BucketType = BucketType.default, *, wait: bool = False ) -> Callable[[T], T]` to solve the following problem:
A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses. This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket -- only a set number of people can run the command. .. versionadded:: 1.3 Parameters ---------- number: :class:`int` The maximum number of invocations of this command that can be running at the same time. per: :class:`.BucketType` The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow it to be used up to ``number`` times per guild. wait: :class:`bool` Whether the command should wait for the queue to be over. If this is set to ``False`` then instead of waiting until the command can run again, the command raises :exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True`` then the command waits until it can be executed.
Here is the function:
def max_concurrency(
number: int, per: BucketType = BucketType.default, *, wait: bool = False
) -> Callable[[T], T]:
"""A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses.
This enables you to only allow a certain number of command invocations at the same time,
for example if a command takes too long or if only one user can use it at a time. This
differs from a cooldown in that there is no set waiting period or token bucket -- only
a set number of people can run the command.
.. versionadded:: 1.3
Parameters
----------
number: :class:`int`
The maximum number of invocations of this command that can be running at the same time.
per: :class:`.BucketType`
The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow
it to be used up to ``number`` times per guild.
wait: :class:`bool`
Whether the command should wait for the queue to be over. If this is set to ``False``
then instead of waiting until the command can run again, the command raises
:exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True``
then the command waits until it can be executed.
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
value = MaxConcurrency(number, per=per, wait=wait)
if isinstance(func, Command):
func._max_concurrency = value
else:
func.__commands_max_concurrency__ = value
return func
return decorator # type: ignore | A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses. This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket -- only a set number of people can run the command. .. versionadded:: 1.3 Parameters ---------- number: :class:`int` The maximum number of invocations of this command that can be running at the same time. per: :class:`.BucketType` The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow it to be used up to ``number`` times per guild. wait: :class:`bool` Whether the command should wait for the queue to be over. If this is set to ``False`` then instead of waiting until the command can run again, the command raises :exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True`` then the command waits until it can be executed. |
160,907 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
class Command(_BaseCommand, Generic[CogT, P, T]):
r"""A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The coroutine that is executed when the command is called.
help: Optional[:class:`str`]
The long help text for the command.
brief: Optional[:class:`str`]
The short help text for the command.
usage: Optional[:class:`str`]
A replacement for arguments in the default help text.
aliases: Union[List[:class:`str`], Tuple[:class:`str`]]
The list of aliases the command can be invoked under.
enabled: :class:`bool`
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
:exc:`.DisabledCommand` is raised to the :func:`.on_command_error`
event. Defaults to ``True``.
parent: Optional[:class:`Group`]
The parent group that this command belongs to. ``None`` if there
isn't one.
cog: Optional[:class:`Cog`]
The cog that this command belongs to. ``None`` if there isn't one.
checks: List[Callable[[:class:`.Context`], :class:`bool`]]
A list of predicates that verifies if the command could be executed
with the given :class:`.Context` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.CommandError` should be used. Note that if the checks fail then
:exc:`.CheckFailure` exception is raised to the :func:`.on_command_error`
event.
description: :class:`str`
The message prefixed into the default help command.
hidden: :class:`bool`
If ``True``\, the default help command does not show this in the
help output.
rest_is_raw: :class:`bool`
If ``False`` and a keyword-only argument is provided then the keyword
only argument is stripped and handled as if it was a regular argument
that handles :exc:`.MissingRequiredArgument` and default values in a
regular matter rather than passing the rest completely raw. If ``True``
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults to ``False``.
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked, if any.
require_var_positional: :class:`bool`
If ``True`` and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults to ``False``.
.. versionadded:: 1.5
ignore_extra: :class:`bool`
If ``True``\, ignores extraneous strings passed to a command if all its
requirements are met (e.g. ``?foo a b c`` when only expecting ``a``
and ``b``). Otherwise :func:`.on_command_error` and local error handlers
are called with :exc:`.TooManyArguments`. Defaults to ``True``.
cooldown_after_parsing: :class:`bool`
If ``True``\, cooldown processing is done after argument parsing,
which calls converters. If ``False`` then cooldown processing is done
first and then the converters are called second. Defaults to ``False``.
extras: :class:`dict`
A dict of user provided extras to attach to the Command.
.. note::
This object may be copied by the library.
.. versionadded:: 2.0
inherit_hooks: :class:`bool`
If ``True`` and this command has a parent :class:`Group` then this command
will inherit all checks, pre_invoke and after_invoke's defined on the the :class:`Group`
This defaults to ``False``
.. note::
Any ``pre_invoke`` or ``after_invoke``'s defined on this will override parent ones.
.. versionadded:: 2.0.0
"""
__original_kwargs__: Dict[str, Any]
def __new__(cls, *_args: Any, **kwargs: Any) -> Self:
# if you're wondering why this is done, it's because we need to ensure
# we have a complete original copy of **kwargs even for classes that
# mess with it by popping before delegating to the subclass __init__.
# In order to do this, we need to control the instance creation and
# inject the original kwargs through __new__ rather than doing it
# inside __init__.
self = super().__new__(cls)
# we do a shallow copy because it's probably the most common use case.
# this could potentially break if someone modifies a list or something
# while it's in movement, but for now this is the cheapest and
# fastest way to do what we want.
self.__original_kwargs__ = kwargs.copy()
return self
def __init__(
self,
func: Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
],
**kwargs: Any,
) -> None:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine.")
name = kwargs.get("name") or func.__name__
if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
self.name: str = name
# ContextT is incompatible with normal Context
self.callback = func # pyright: ignore
self.enabled: bool = kwargs.get("enabled", True)
help_doc = kwargs.get("help")
if help_doc is not None:
help_doc = inspect.cleandoc(help_doc)
else:
help_doc = inspect.getdoc(func)
if isinstance(help_doc, bytes):
help_doc = help_doc.decode("utf-8")
self.help: Optional[str] = help_doc
self.brief: Optional[str] = kwargs.get("brief")
self.usage: Optional[str] = kwargs.get("usage")
self.rest_is_raw: bool = kwargs.get("rest_is_raw", False)
self.aliases: Union[List[str], Tuple[str]] = kwargs.get("aliases", [])
self.extras: Dict[str, Any] = kwargs.get("extras", {})
if not isinstance(self.aliases, (list, tuple)):
raise TypeError("Aliases of a command must be a list or a tuple of strings.")
self.description: str = inspect.cleandoc(kwargs.get("description", ""))
self.hidden: bool = kwargs.get("hidden", False)
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks: List[Check] = checks
try:
cooldown = func.__commands_cooldown__
except AttributeError:
cooldown = kwargs.get("cooldown")
if cooldown is None:
buckets = CooldownMapping(cooldown, BucketType.default)
elif isinstance(cooldown, CooldownMapping):
buckets = cooldown
else:
raise TypeError("Cooldown must be an instance of CooldownMapping or None.")
self._buckets: CooldownMapping = buckets
try:
max_concurrency = func.__commands_max_concurrency__
except AttributeError:
max_concurrency = kwargs.get("max_concurrency")
self._max_concurrency: Optional[MaxConcurrency] = max_concurrency
self.require_var_positional: bool = kwargs.get("require_var_positional", False)
self.ignore_extra: bool = kwargs.get("ignore_extra", True)
self.cooldown_after_parsing: bool = kwargs.get("cooldown_after_parsing", False)
self.cog: Optional[CogT] = None
# bandaid for the fact that sometimes parent can be the bot instance
parent = kwargs.get("parent")
self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore
self._before_invoke: Optional[Hook] = None
try:
before_invoke = func.__before_invoke__
except AttributeError:
pass
else:
self.before_invoke(before_invoke)
self._after_invoke: Optional[Hook] = None
try:
after_invoke = func.__after_invoke__
except AttributeError:
pass
else:
self.after_invoke(after_invoke)
# Attempt to bind to parent hooks if applicable
if not kwargs.get("inherit_hooks", False):
return
# We should be binding hooks
if not self.parent:
return
inherited_before_invoke: Optional[Hook] = None
try:
inherited_before_invoke = self.parent._before_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_before_invoke:
self.before_invoke(inherited_before_invoke)
inherited_after_invoke: Optional[Hook] = None
try:
inherited_after_invoke = self.parent._after_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_after_invoke:
self.after_invoke(inherited_after_invoke)
self.checks.extend(self.parent.checks) # type: ignore
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_guild_permissions", {})
def callback(
self,
) -> Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]:
return self._callback
def callback(
self,
function: Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
],
) -> None:
self._callback = function
unwrap = unwrap_function(function)
self.module = unwrap.__module__
try:
globalns = unwrap.__globals__
except AttributeError:
globalns = {}
self.params = get_signature_parameters(function, globalns)
def add_check(self, func: Check) -> None:
"""Adds a check to the command.
This is the non-decorator interface to :func:`.check`.
.. versionadded:: 1.3
Parameters
----------
func
The function that will be used as a check.
"""
self.checks.append(func)
def remove_check(self, func: Check) -> None:
"""Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command's checks.
.. versionadded:: 1.3
Parameters
----------
func
The function to remove from the checks.
"""
with contextlib.suppress(ValueError):
self.checks.remove(func)
def update(self, **kwargs: Any) -> None:
"""Updates :class:`Command` instance with updated attribute.
This works similarly to the :func:`.command` decorator in terms
of parameters in that they are passed to the :class:`Command` or
subclass constructors, sans the name and callback.
"""
self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs))
async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T:
"""|coro|
Calls the internal callback that the command holds.
.. note::
This bypasses all mechanisms -- including checks, converters,
invoke hooks, cooldowns, etc. You must take care to pass
the proper arguments and types to this function.
.. versionadded:: 1.3
"""
if self.cog is not None:
return await self.callback(self.cog, context, *args, **kwargs) # type: ignore
return await self.callback(context, *args, **kwargs) # type: ignore
def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT:
other._before_invoke = self._before_invoke
other._after_invoke = self._after_invoke
if self.checks != other.checks:
other.checks = self.checks.copy()
if self._buckets.valid and not other._buckets.valid:
other._buckets = self._buckets.copy()
if self._max_concurrency != other._max_concurrency:
# _max_concurrency won't be None at this point
other._max_concurrency = self._max_concurrency.copy() # type: ignore
with contextlib.suppress(AttributeError):
other.on_error = self.on_error
return other
def copy(self) -> Self:
"""Creates a copy of this command.
Returns
-------
:class:`Command`
A new instance of this command.
"""
ret = self.__class__(self.callback, **self.__original_kwargs__)
return self._ensure_assignment_on_copy(ret)
def _update_copy(self, kwargs: Dict[str, Any]) -> Self:
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = self.__class__(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
return self.copy()
async def dispatch_error(self, ctx: Context, error: Exception) -> None:
ctx.command_failed = True
cog = self.cog
try:
coro = self.on_error
except AttributeError:
pass
else:
injected = wrap_callback(coro)
if cog is not None:
await injected(cog, ctx, error)
else:
await injected(ctx, error)
try:
if cog is not None:
local = Cog._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch("command_error", ctx, error)
async def transform(self, ctx: Context, param: inspect.Parameter) -> Any:
required = param.default is param.empty
converter = get_converter(param)
consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw
view = ctx.view
view.skip_ws()
# The greedy converter is simple -- it keeps going until it fails in which case,
# it undos the view ready for the next parameter to use instead
if isinstance(converter, Greedy):
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
return await self._transform_greedy_pos(ctx, param, required, converter.converter)
if param.kind == param.VAR_POSITIONAL:
return await self._transform_greedy_var_pos(ctx, param, converter.converter)
# if we're here, then it's a KEYWORD_ONLY param type
# since this is mostly useless, we'll helpfully transform Greedy[X]
# into just X and do the parsing that way.
converter = converter.converter
if view.eof:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError # break the loop
if required:
if self._is_typing_optional(param.annotation):
return None
if hasattr(converter, "__commands_is_flag__") and converter._can_be_constructible():
return await converter._construct_default(ctx)
raise MissingRequiredArgument(param)
return param.default
previous = view.index
if consume_rest_is_special:
argument = view.read_rest().strip()
else:
try:
argument = view.get_quoted_word()
except ArgumentParsingError:
if self._is_typing_optional(param.annotation):
view.index = previous
return None
raise
view.previous = previous
if argument is None:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError
if required:
if self._is_typing_optional(param.annotation):
return None
raise MissingRequiredArgument(param)
return param.default
# type-checker fails to narrow argument
return await run_converters(ctx, converter, argument, param)
async def _transform_greedy_pos(
self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any
) -> Any:
view = ctx.view
result = []
while not view.eof:
# for use with a manual undo
previous = view.index
view.skip_ws()
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
break
else:
result.append(value)
if not result and not required:
return param.default
return result
async def _transform_greedy_var_pos(
self, ctx: Context, param: inspect.Parameter, converter: Any
) -> Any:
view = ctx.view
previous = view.index
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
raise RuntimeError from None # break loop
else:
return value
def clean_params(self) -> Dict[str, inspect.Parameter]:
"""Dict[:class:`str`, :class:`inspect.Parameter`]:
Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'self' parameter") from None
try:
# first/second parameter is context
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'context' parameter") from None
return result
def full_parent_name(self) -> str:
""":class:`str`: Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``.
"""
entries = []
command = self
# command.parent is type-hinted as GroupMixin some attributes are resolved via MRO
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command.name) # type: ignore
return " ".join(reversed(entries))
def parents(self) -> List[Group]:
"""List[:class:`Group`]: Retrieves the parents of this command.
If the command has no parents then it returns an empty :class:`list`.
For example in commands ``?a b c test``, the parents are ``[c, b, a]``.
.. versionadded:: 1.1
"""
entries = []
command = self
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command)
return entries
def root_parent(self) -> Optional[Group]:
"""Optional[:class:`Group`]: Retrieves the root parent of this command.
If the command has no parents then it returns ``None``.
For example in commands ``?a b c test``, the root parent is ``a``.
"""
if not self.parent:
return None
return self.parents[-1]
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return parent + " " + self.name
return self.name
def __str__(self) -> str:
return self.qualified_name
async def _parse_arguments(self, ctx: Context) -> None:
ctx.args = [ctx] if self.cog is None else [self.cog, ctx]
ctx.kwargs = {}
args = ctx.args
kwargs = ctx.kwargs
view = ctx.view
iterator = iter(self.params.items())
if self.cog is not None:
# we have 'self' as the first parameter so just advance
# the iterator and resume parsing
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "self" parameter.'
) from None
# next we have the 'ctx' as the next parameter
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "ctx" parameter.'
) from None
for name, param in iterator:
ctx.current_parameter = param
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
transformed = await self.transform(ctx, param)
args.append(transformed)
elif param.kind == param.KEYWORD_ONLY:
# kwarg only param denotes "consume rest" semantics
if self.rest_is_raw:
converter = get_converter(param)
argument = view.read_rest()
kwargs[name] = await run_converters(ctx, converter, argument, param)
else:
kwargs[name] = await self.transform(ctx, param)
break
elif param.kind == param.VAR_POSITIONAL:
if view.eof and self.require_var_positional:
raise MissingRequiredArgument(param)
while not view.eof:
try:
transformed = await self.transform(ctx, param)
args.append(transformed)
except RuntimeError:
break
if not self.ignore_extra and not view.eof:
raise TooManyArguments("Too many arguments passed to " + self.qualified_name)
async def call_before_hooks(self, ctx: Context) -> None:
# now that we're done preparing we can call the pre-command hooks
# first, call the command local hook:
cog = self.cog
if self._before_invoke is not None:
# should be cog if @commands.before_invoke is used
instance = getattr(self._before_invoke, "__self__", cog)
# __self__ only exists for methods, not functions
# however, if @command.before_invoke is used, it will be a function
if instance:
await self._before_invoke(instance, ctx) # type: ignore
else:
await self._before_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_before_invoke)
if hook is not None:
await hook(ctx)
# call the bot global hook if necessary
hook = ctx.bot._before_invoke
if hook is not None:
await hook(ctx)
async def call_after_hooks(self, ctx: Context) -> None:
cog = self.cog
if self._after_invoke is not None:
instance = getattr(self._after_invoke, "__self__", cog)
if instance:
await self._after_invoke(instance, ctx) # type: ignore
else:
await self._after_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
def _prepare_cooldowns(self, ctx: Context) -> None:
if self._buckets.valid:
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
bucket = self._buckets.get_bucket(ctx.message, current)
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
async def prepare(self, ctx: Context) -> None:
ctx.command = self
if not await self.can_run(ctx):
raise CheckFailure(f"The check functions for command {self.qualified_name} failed.")
if self._max_concurrency is not None:
# For this application, context can be duck-typed as a Message
await self._max_concurrency.acquire(ctx) # type: ignore
try:
if self.cooldown_after_parsing:
await self._parse_arguments(ctx)
self._prepare_cooldowns(ctx)
else:
self._prepare_cooldowns(ctx)
await self._parse_arguments(ctx)
await self.call_before_hooks(ctx)
except:
if self._max_concurrency is not None:
await self._max_concurrency.release(ctx) # type: ignore
raise
def is_on_cooldown(self, ctx: Context) -> bool:
"""Checks whether the command is currently on cooldown.
Parameters
----------
ctx: :class:`.Context`
The invocation context to use when checking the commands cooldown status.
Returns
-------
:class:`bool`
A boolean indicating if the command is on cooldown.
"""
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_tokens(current) == 0
def reset_cooldown(self, ctx: Context) -> None:
"""Resets the cooldown on this command.
Parameters
----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.reset()
def get_cooldown_retry_after(self, ctx: Context) -> float:
"""Retrieves the amount of seconds before this command can be tried again.
.. versionadded:: 1.4
Parameters
----------
ctx: :class:`.Context`
The invocation context to retrieve the cooldown from.
Returns
-------
:class:`float`
The amount of time left on this command's cooldown in seconds.
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_retry_after(current)
return 0.0
async def invoke(self, ctx: Context) -> None:
await self.prepare(ctx)
# terminate the invoked_subcommand chain.
# since we're in a regular command (and not a group) then
# the invoked subcommand is None.
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
ctx.invoked_subcommand = None
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
def error(self, coro: ErrorT) -> ErrorT:
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The error handler must be a coroutine.")
self.on_error: Error = coro
return coro
def has_error_handler(self) -> bool:
""":class:`bool`: Checks whether the command has an error handler registered.
.. versionadded:: 1.7
"""
return hasattr(self, "on_error")
def before_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The pre-invoke hook must be a coroutine.")
self._before_invoke = coro
return coro
def after_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The post-invoke hook must be a coroutine.")
self._after_invoke = coro
return coro
def cog_name(self) -> Optional[str]:
"""Optional[:class:`str`]: The name of the cog this command belongs to, if any."""
return type(self.cog).__cog_name__ if self.cog is not None else None
def short_doc(self) -> str:
""":class:`str`: Gets the "short" documentation of a command.
By default, this is the :attr:`.brief` attribute.
If that lookup leads to an empty string then the first line of the
:attr:`.help` attribute is used instead.
"""
if self.brief is not None:
return self.brief
if self.help is not None:
return self.help.split("\n", 1)[0]
return ""
def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]:
return getattr(annotation, "__origin__", None) is Union and type(None) in annotation.__args__ # type: ignore
def signature(self) -> str:
""":class:`str`: Returns a POSIX-like signature useful for help command output."""
if self.usage is not None:
return self.usage
params = self.clean_params
if not params:
return ""
result = []
for name, param in params.items():
greedy = isinstance(param.annotation, Greedy)
optional = False # postpone evaluation of if it's an optional argument
# for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the
# parameter signature is a literal list of it's values
annotation = param.annotation.converter if greedy else param.annotation
origin = getattr(annotation, "__origin__", None)
if not greedy and origin is Union:
none_cls = type(None)
union_args = annotation.__args__
optional = union_args[-1] is none_cls
if len(union_args) == 2 and optional:
annotation = union_args[0]
origin = getattr(annotation, "__origin__", None)
if origin is Literal:
name = "|".join(
f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__
)
if param.default is not param.empty:
# We don't want None or '' to trigger the [name=value] case and instead it should
# do [name] since [name=None] or [name=] are not exactly useful for the user.
should_print = (
param.default if isinstance(param.default, str) else param.default is not None
)
if should_print:
result.append(
f"[{name}={param.default}]"
if not greedy
else f"[{name}={param.default}]..."
)
continue
result.append(f"[{name}]")
elif param.kind == param.VAR_POSITIONAL:
if self.require_var_positional:
result.append(f"<{name}...>")
else:
result.append(f"[{name}...]")
elif greedy:
result.append(f"[{name}]...")
elif optional:
result.append(f"[{name}]")
else:
result.append(f"<{name}>")
return " ".join(result)
async def can_run(self, ctx: Context) -> bool:
"""|coro|
Checks if the command can be executed by checking all the predicates
inside the :attr:`~Command.checks` attribute. This also checks whether the
command is disabled.
.. versionchanged:: 1.3
Checks whether the command is disabled or not
Parameters
----------
ctx: :class:`.Context`
The ctx of the command currently being invoked.
Raises
------
:class:`CommandError`
Any command error that was raised during a check call will be propagated
by this function.
Returns
-------
:class:`bool`
A boolean indicating if the command can be invoked.
"""
if not self.enabled:
raise DisabledCommand(f"{self.name} command is disabled")
original = ctx.command
ctx.command = self
try:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.qualified_name} failed."
)
cog = self.cog
if cog is not None:
local_check = Cog._get_overridden_method(cog.cog_check)
if local_check is not None:
ret = await nextcord.utils.maybe_coroutine(local_check, ctx)
if not ret:
return False
predicates = self.checks
if not predicates:
# since we have no checks, then we just return True.
return True
return await nextcord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
finally:
ctx.command = original
CoroFunc = Callable[..., Coro[Any]]
The provided code snippet includes necessary dependencies for implementing the `before_invoke` function. Write a Python function `def before_invoke(coro) -> Callable[[T], T]` to solve the following problem:
A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 Example ------- .. code-block:: python3 async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Cog): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me') bot.add_cog(What())
Here is the function:
def before_invoke(coro) -> Callable[[T], T]:
"""A decorator that registers a coroutine as a pre-invoke hook.
This allows you to refer to one before invoke hook for several commands that
do not have to be within the same cog.
.. versionadded:: 1.4
Example
-------
.. code-block:: python3
async def record_usage(ctx):
print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)
@bot.command()
@commands.before_invoke(record_usage)
async def who(ctx): # Output: <User> used who at <Time>
await ctx.send('i am a bot')
class What(commands.Cog):
@commands.before_invoke(record_usage)
@commands.command()
async def when(self, ctx): # Output: <User> used when at <Time>
await ctx.send(f'and i have existed since {ctx.bot.user.created_at}')
@commands.command()
async def where(self, ctx): # Output: <Nothing>
await ctx.send('on Discord')
@commands.command()
async def why(self, ctx): # Output: <Nothing>
await ctx.send('because someone made me')
bot.add_cog(What())
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.before_invoke(coro)
else:
func.__before_invoke__ = coro
return func
return decorator # type: ignore | A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 Example ------- .. code-block:: python3 async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Cog): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Discord') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me') bot.add_cog(What()) |
160,908 | from __future__ import annotations
import asyncio
import contextlib
import datetime
import functools
import inspect
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
import nextcord
from ._types import _BaseCommand
from .cog import Cog
from .context import Context
from .converter import Greedy, get_converter, run_converters
from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency
from .errors import *
T = TypeVar("T")
class Command(_BaseCommand, Generic[CogT, P, T]):
r"""A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The coroutine that is executed when the command is called.
help: Optional[:class:`str`]
The long help text for the command.
brief: Optional[:class:`str`]
The short help text for the command.
usage: Optional[:class:`str`]
A replacement for arguments in the default help text.
aliases: Union[List[:class:`str`], Tuple[:class:`str`]]
The list of aliases the command can be invoked under.
enabled: :class:`bool`
A boolean that indicates if the command is currently enabled.
If the command is invoked while it is disabled, then
:exc:`.DisabledCommand` is raised to the :func:`.on_command_error`
event. Defaults to ``True``.
parent: Optional[:class:`Group`]
The parent group that this command belongs to. ``None`` if there
isn't one.
cog: Optional[:class:`Cog`]
The cog that this command belongs to. ``None`` if there isn't one.
checks: List[Callable[[:class:`.Context`], :class:`bool`]]
A list of predicates that verifies if the command could be executed
with the given :class:`.Context` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.CommandError` should be used. Note that if the checks fail then
:exc:`.CheckFailure` exception is raised to the :func:`.on_command_error`
event.
description: :class:`str`
The message prefixed into the default help command.
hidden: :class:`bool`
If ``True``\, the default help command does not show this in the
help output.
rest_is_raw: :class:`bool`
If ``False`` and a keyword-only argument is provided then the keyword
only argument is stripped and handled as if it was a regular argument
that handles :exc:`.MissingRequiredArgument` and default values in a
regular matter rather than passing the rest completely raw. If ``True``
then the keyword-only argument will pass in the rest of the arguments
in a completely raw matter. Defaults to ``False``.
invoked_subcommand: Optional[:class:`Command`]
The subcommand that was invoked, if any.
require_var_positional: :class:`bool`
If ``True`` and a variadic positional argument is specified, requires
the user to specify at least one argument. Defaults to ``False``.
.. versionadded:: 1.5
ignore_extra: :class:`bool`
If ``True``\, ignores extraneous strings passed to a command if all its
requirements are met (e.g. ``?foo a b c`` when only expecting ``a``
and ``b``). Otherwise :func:`.on_command_error` and local error handlers
are called with :exc:`.TooManyArguments`. Defaults to ``True``.
cooldown_after_parsing: :class:`bool`
If ``True``\, cooldown processing is done after argument parsing,
which calls converters. If ``False`` then cooldown processing is done
first and then the converters are called second. Defaults to ``False``.
extras: :class:`dict`
A dict of user provided extras to attach to the Command.
.. note::
This object may be copied by the library.
.. versionadded:: 2.0
inherit_hooks: :class:`bool`
If ``True`` and this command has a parent :class:`Group` then this command
will inherit all checks, pre_invoke and after_invoke's defined on the the :class:`Group`
This defaults to ``False``
.. note::
Any ``pre_invoke`` or ``after_invoke``'s defined on this will override parent ones.
.. versionadded:: 2.0.0
"""
__original_kwargs__: Dict[str, Any]
def __new__(cls, *_args: Any, **kwargs: Any) -> Self:
# if you're wondering why this is done, it's because we need to ensure
# we have a complete original copy of **kwargs even for classes that
# mess with it by popping before delegating to the subclass __init__.
# In order to do this, we need to control the instance creation and
# inject the original kwargs through __new__ rather than doing it
# inside __init__.
self = super().__new__(cls)
# we do a shallow copy because it's probably the most common use case.
# this could potentially break if someone modifies a list or something
# while it's in movement, but for now this is the cheapest and
# fastest way to do what we want.
self.__original_kwargs__ = kwargs.copy()
return self
def __init__(
self,
func: Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
],
**kwargs: Any,
) -> None:
if not asyncio.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine.")
name = kwargs.get("name") or func.__name__
if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
self.name: str = name
# ContextT is incompatible with normal Context
self.callback = func # pyright: ignore
self.enabled: bool = kwargs.get("enabled", True)
help_doc = kwargs.get("help")
if help_doc is not None:
help_doc = inspect.cleandoc(help_doc)
else:
help_doc = inspect.getdoc(func)
if isinstance(help_doc, bytes):
help_doc = help_doc.decode("utf-8")
self.help: Optional[str] = help_doc
self.brief: Optional[str] = kwargs.get("brief")
self.usage: Optional[str] = kwargs.get("usage")
self.rest_is_raw: bool = kwargs.get("rest_is_raw", False)
self.aliases: Union[List[str], Tuple[str]] = kwargs.get("aliases", [])
self.extras: Dict[str, Any] = kwargs.get("extras", {})
if not isinstance(self.aliases, (list, tuple)):
raise TypeError("Aliases of a command must be a list or a tuple of strings.")
self.description: str = inspect.cleandoc(kwargs.get("description", ""))
self.hidden: bool = kwargs.get("hidden", False)
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks: List[Check] = checks
try:
cooldown = func.__commands_cooldown__
except AttributeError:
cooldown = kwargs.get("cooldown")
if cooldown is None:
buckets = CooldownMapping(cooldown, BucketType.default)
elif isinstance(cooldown, CooldownMapping):
buckets = cooldown
else:
raise TypeError("Cooldown must be an instance of CooldownMapping or None.")
self._buckets: CooldownMapping = buckets
try:
max_concurrency = func.__commands_max_concurrency__
except AttributeError:
max_concurrency = kwargs.get("max_concurrency")
self._max_concurrency: Optional[MaxConcurrency] = max_concurrency
self.require_var_positional: bool = kwargs.get("require_var_positional", False)
self.ignore_extra: bool = kwargs.get("ignore_extra", True)
self.cooldown_after_parsing: bool = kwargs.get("cooldown_after_parsing", False)
self.cog: Optional[CogT] = None
# bandaid for the fact that sometimes parent can be the bot instance
parent = kwargs.get("parent")
self.parent: Optional[GroupMixin] = parent if isinstance(parent, _BaseCommand) else None # type: ignore
self._before_invoke: Optional[Hook] = None
try:
before_invoke = func.__before_invoke__
except AttributeError:
pass
else:
self.before_invoke(before_invoke)
self._after_invoke: Optional[Hook] = None
try:
after_invoke = func.__after_invoke__
except AttributeError:
pass
else:
self.after_invoke(after_invoke)
# Attempt to bind to parent hooks if applicable
if not kwargs.get("inherit_hooks", False):
return
# We should be binding hooks
if not self.parent:
return
inherited_before_invoke: Optional[Hook] = None
try:
inherited_before_invoke = self.parent._before_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_before_invoke:
self.before_invoke(inherited_before_invoke)
inherited_after_invoke: Optional[Hook] = None
try:
inherited_after_invoke = self.parent._after_invoke # type: ignore
except AttributeError:
pass
else:
if inherited_after_invoke:
self.after_invoke(inherited_after_invoke)
self.checks.extend(self.parent.checks) # type: ignore
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__required_bot_guild_permissions", {})
def callback(
self,
) -> Union[
Callable[Concatenate[CogT, ContextT, P], Coro[T]],
Callable[Concatenate[ContextT, P], Coro[T]],
]:
return self._callback
def callback(
self,
function: Union[
Callable[Concatenate[CogT, Context, P], Coro[T]],
Callable[Concatenate[Context, P], Coro[T]],
],
) -> None:
self._callback = function
unwrap = unwrap_function(function)
self.module = unwrap.__module__
try:
globalns = unwrap.__globals__
except AttributeError:
globalns = {}
self.params = get_signature_parameters(function, globalns)
def add_check(self, func: Check) -> None:
"""Adds a check to the command.
This is the non-decorator interface to :func:`.check`.
.. versionadded:: 1.3
Parameters
----------
func
The function that will be used as a check.
"""
self.checks.append(func)
def remove_check(self, func: Check) -> None:
"""Removes a check from the command.
This function is idempotent and will not raise an exception
if the function is not in the command's checks.
.. versionadded:: 1.3
Parameters
----------
func
The function to remove from the checks.
"""
with contextlib.suppress(ValueError):
self.checks.remove(func)
def update(self, **kwargs: Any) -> None:
"""Updates :class:`Command` instance with updated attribute.
This works similarly to the :func:`.command` decorator in terms
of parameters in that they are passed to the :class:`Command` or
subclass constructors, sans the name and callback.
"""
self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs))
async def __call__(self, context: Context, *args: P.args, **kwargs: P.kwargs) -> T:
"""|coro|
Calls the internal callback that the command holds.
.. note::
This bypasses all mechanisms -- including checks, converters,
invoke hooks, cooldowns, etc. You must take care to pass
the proper arguments and types to this function.
.. versionadded:: 1.3
"""
if self.cog is not None:
return await self.callback(self.cog, context, *args, **kwargs) # type: ignore
return await self.callback(context, *args, **kwargs) # type: ignore
def _ensure_assignment_on_copy(self, other: CommandT) -> CommandT:
other._before_invoke = self._before_invoke
other._after_invoke = self._after_invoke
if self.checks != other.checks:
other.checks = self.checks.copy()
if self._buckets.valid and not other._buckets.valid:
other._buckets = self._buckets.copy()
if self._max_concurrency != other._max_concurrency:
# _max_concurrency won't be None at this point
other._max_concurrency = self._max_concurrency.copy() # type: ignore
with contextlib.suppress(AttributeError):
other.on_error = self.on_error
return other
def copy(self) -> Self:
"""Creates a copy of this command.
Returns
-------
:class:`Command`
A new instance of this command.
"""
ret = self.__class__(self.callback, **self.__original_kwargs__)
return self._ensure_assignment_on_copy(ret)
def _update_copy(self, kwargs: Dict[str, Any]) -> Self:
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = self.__class__(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
return self.copy()
async def dispatch_error(self, ctx: Context, error: Exception) -> None:
ctx.command_failed = True
cog = self.cog
try:
coro = self.on_error
except AttributeError:
pass
else:
injected = wrap_callback(coro)
if cog is not None:
await injected(cog, ctx, error)
else:
await injected(ctx, error)
try:
if cog is not None:
local = Cog._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch("command_error", ctx, error)
async def transform(self, ctx: Context, param: inspect.Parameter) -> Any:
required = param.default is param.empty
converter = get_converter(param)
consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw
view = ctx.view
view.skip_ws()
# The greedy converter is simple -- it keeps going until it fails in which case,
# it undos the view ready for the next parameter to use instead
if isinstance(converter, Greedy):
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
return await self._transform_greedy_pos(ctx, param, required, converter.converter)
if param.kind == param.VAR_POSITIONAL:
return await self._transform_greedy_var_pos(ctx, param, converter.converter)
# if we're here, then it's a KEYWORD_ONLY param type
# since this is mostly useless, we'll helpfully transform Greedy[X]
# into just X and do the parsing that way.
converter = converter.converter
if view.eof:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError # break the loop
if required:
if self._is_typing_optional(param.annotation):
return None
if hasattr(converter, "__commands_is_flag__") and converter._can_be_constructible():
return await converter._construct_default(ctx)
raise MissingRequiredArgument(param)
return param.default
previous = view.index
if consume_rest_is_special:
argument = view.read_rest().strip()
else:
try:
argument = view.get_quoted_word()
except ArgumentParsingError:
if self._is_typing_optional(param.annotation):
view.index = previous
return None
raise
view.previous = previous
if argument is None:
if param.kind == param.VAR_POSITIONAL:
raise RuntimeError
if required:
if self._is_typing_optional(param.annotation):
return None
raise MissingRequiredArgument(param)
return param.default
# type-checker fails to narrow argument
return await run_converters(ctx, converter, argument, param)
async def _transform_greedy_pos(
self, ctx: Context, param: inspect.Parameter, required: bool, converter: Any
) -> Any:
view = ctx.view
result = []
while not view.eof:
# for use with a manual undo
previous = view.index
view.skip_ws()
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
break
else:
result.append(value)
if not result and not required:
return param.default
return result
async def _transform_greedy_var_pos(
self, ctx: Context, param: inspect.Parameter, converter: Any
) -> Any:
view = ctx.view
previous = view.index
try:
argument = view.get_quoted_word()
value = await run_converters(ctx, converter, argument, param) # type: ignore
except (CommandError, ArgumentParsingError):
view.index = previous
raise RuntimeError from None # break loop
else:
return value
def clean_params(self) -> Dict[str, inspect.Parameter]:
"""Dict[:class:`str`, :class:`inspect.Parameter`]:
Retrieves the parameter dictionary without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'self' parameter") from None
try:
# first/second parameter is context
del result[next(iter(result))]
except StopIteration:
raise ValueError("missing 'context' parameter") from None
return result
def full_parent_name(self) -> str:
""":class:`str`: Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``.
"""
entries = []
command = self
# command.parent is type-hinted as GroupMixin some attributes are resolved via MRO
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command.name) # type: ignore
return " ".join(reversed(entries))
def parents(self) -> List[Group]:
"""List[:class:`Group`]: Retrieves the parents of this command.
If the command has no parents then it returns an empty :class:`list`.
For example in commands ``?a b c test``, the parents are ``[c, b, a]``.
.. versionadded:: 1.1
"""
entries = []
command = self
while command.parent is not None: # type: ignore
command = command.parent
entries.append(command)
return entries
def root_parent(self) -> Optional[Group]:
"""Optional[:class:`Group`]: Retrieves the root parent of this command.
If the command has no parents then it returns ``None``.
For example in commands ``?a b c test``, the root parent is ``a``.
"""
if not self.parent:
return None
return self.parents[-1]
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return parent + " " + self.name
return self.name
def __str__(self) -> str:
return self.qualified_name
async def _parse_arguments(self, ctx: Context) -> None:
ctx.args = [ctx] if self.cog is None else [self.cog, ctx]
ctx.kwargs = {}
args = ctx.args
kwargs = ctx.kwargs
view = ctx.view
iterator = iter(self.params.items())
if self.cog is not None:
# we have 'self' as the first parameter so just advance
# the iterator and resume parsing
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "self" parameter.'
) from None
# next we have the 'ctx' as the next parameter
try:
next(iterator)
except StopIteration:
raise nextcord.ClientException(
f'Callback for {self.name} command is missing "ctx" parameter.'
) from None
for name, param in iterator:
ctx.current_parameter = param
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY):
transformed = await self.transform(ctx, param)
args.append(transformed)
elif param.kind == param.KEYWORD_ONLY:
# kwarg only param denotes "consume rest" semantics
if self.rest_is_raw:
converter = get_converter(param)
argument = view.read_rest()
kwargs[name] = await run_converters(ctx, converter, argument, param)
else:
kwargs[name] = await self.transform(ctx, param)
break
elif param.kind == param.VAR_POSITIONAL:
if view.eof and self.require_var_positional:
raise MissingRequiredArgument(param)
while not view.eof:
try:
transformed = await self.transform(ctx, param)
args.append(transformed)
except RuntimeError:
break
if not self.ignore_extra and not view.eof:
raise TooManyArguments("Too many arguments passed to " + self.qualified_name)
async def call_before_hooks(self, ctx: Context) -> None:
# now that we're done preparing we can call the pre-command hooks
# first, call the command local hook:
cog = self.cog
if self._before_invoke is not None:
# should be cog if @commands.before_invoke is used
instance = getattr(self._before_invoke, "__self__", cog)
# __self__ only exists for methods, not functions
# however, if @command.before_invoke is used, it will be a function
if instance:
await self._before_invoke(instance, ctx) # type: ignore
else:
await self._before_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_before_invoke)
if hook is not None:
await hook(ctx)
# call the bot global hook if necessary
hook = ctx.bot._before_invoke
if hook is not None:
await hook(ctx)
async def call_after_hooks(self, ctx: Context) -> None:
cog = self.cog
if self._after_invoke is not None:
instance = getattr(self._after_invoke, "__self__", cog)
if instance:
await self._after_invoke(instance, ctx) # type: ignore
else:
await self._after_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = Cog._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
def _prepare_cooldowns(self, ctx: Context) -> None:
if self._buckets.valid:
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
bucket = self._buckets.get_bucket(ctx.message, current)
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
async def prepare(self, ctx: Context) -> None:
ctx.command = self
if not await self.can_run(ctx):
raise CheckFailure(f"The check functions for command {self.qualified_name} failed.")
if self._max_concurrency is not None:
# For this application, context can be duck-typed as a Message
await self._max_concurrency.acquire(ctx) # type: ignore
try:
if self.cooldown_after_parsing:
await self._parse_arguments(ctx)
self._prepare_cooldowns(ctx)
else:
self._prepare_cooldowns(ctx)
await self._parse_arguments(ctx)
await self.call_before_hooks(ctx)
except:
if self._max_concurrency is not None:
await self._max_concurrency.release(ctx) # type: ignore
raise
def is_on_cooldown(self, ctx: Context) -> bool:
"""Checks whether the command is currently on cooldown.
Parameters
----------
ctx: :class:`.Context`
The invocation context to use when checking the commands cooldown status.
Returns
-------
:class:`bool`
A boolean indicating if the command is on cooldown.
"""
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_tokens(current) == 0
def reset_cooldown(self, ctx: Context) -> None:
"""Resets the cooldown on this command.
Parameters
----------
ctx: :class:`.Context`
The invocation context to reset the cooldown under.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.reset()
def get_cooldown_retry_after(self, ctx: Context) -> float:
"""Retrieves the amount of seconds before this command can be tried again.
.. versionadded:: 1.4
Parameters
----------
ctx: :class:`.Context`
The invocation context to retrieve the cooldown from.
Returns
-------
:class:`float`
The amount of time left on this command's cooldown in seconds.
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
return bucket.get_retry_after(current)
return 0.0
async def invoke(self, ctx: Context) -> None:
await self.prepare(ctx)
# terminate the invoked_subcommand chain.
# since we're in a regular command (and not a group) then
# the invoked subcommand is None.
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
injected = hooked_wrapped_callback(self, ctx, self.callback)
await injected(*ctx.args, **ctx.kwargs)
async def reinvoke(self, ctx: Context, *, call_hooks: bool = False) -> None:
ctx.command = self
await self._parse_arguments(ctx)
if call_hooks:
await self.call_before_hooks(ctx)
ctx.invoked_subcommand = None
try:
await self.callback(*ctx.args, **ctx.kwargs) # type: ignore
except:
ctx.command_failed = True
raise
finally:
if call_hooks:
await self.call_after_hooks(ctx)
def error(self, coro: ErrorT) -> ErrorT:
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The error handler must be a coroutine.")
self.on_error: Error = coro
return coro
def has_error_handler(self) -> bool:
""":class:`bool`: Checks whether the command has an error handler registered.
.. versionadded:: 1.7
"""
return hasattr(self, "on_error")
def before_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The pre-invoke hook must be a coroutine.")
self._before_invoke = coro
return coro
def after_invoke(self, coro: HookT) -> HookT:
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The post-invoke hook must be a coroutine.")
self._after_invoke = coro
return coro
def cog_name(self) -> Optional[str]:
"""Optional[:class:`str`]: The name of the cog this command belongs to, if any."""
return type(self.cog).__cog_name__ if self.cog is not None else None
def short_doc(self) -> str:
""":class:`str`: Gets the "short" documentation of a command.
By default, this is the :attr:`.brief` attribute.
If that lookup leads to an empty string then the first line of the
:attr:`.help` attribute is used instead.
"""
if self.brief is not None:
return self.brief
if self.help is not None:
return self.help.split("\n", 1)[0]
return ""
def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> TypeGuard[Optional[T]]:
return getattr(annotation, "__origin__", None) is Union and type(None) in annotation.__args__ # type: ignore
def signature(self) -> str:
""":class:`str`: Returns a POSIX-like signature useful for help command output."""
if self.usage is not None:
return self.usage
params = self.clean_params
if not params:
return ""
result = []
for name, param in params.items():
greedy = isinstance(param.annotation, Greedy)
optional = False # postpone evaluation of if it's an optional argument
# for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the
# parameter signature is a literal list of it's values
annotation = param.annotation.converter if greedy else param.annotation
origin = getattr(annotation, "__origin__", None)
if not greedy and origin is Union:
none_cls = type(None)
union_args = annotation.__args__
optional = union_args[-1] is none_cls
if len(union_args) == 2 and optional:
annotation = union_args[0]
origin = getattr(annotation, "__origin__", None)
if origin is Literal:
name = "|".join(
f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__
)
if param.default is not param.empty:
# We don't want None or '' to trigger the [name=value] case and instead it should
# do [name] since [name=None] or [name=] are not exactly useful for the user.
should_print = (
param.default if isinstance(param.default, str) else param.default is not None
)
if should_print:
result.append(
f"[{name}={param.default}]"
if not greedy
else f"[{name}={param.default}]..."
)
continue
result.append(f"[{name}]")
elif param.kind == param.VAR_POSITIONAL:
if self.require_var_positional:
result.append(f"<{name}...>")
else:
result.append(f"[{name}...]")
elif greedy:
result.append(f"[{name}]...")
elif optional:
result.append(f"[{name}]")
else:
result.append(f"<{name}>")
return " ".join(result)
async def can_run(self, ctx: Context) -> bool:
"""|coro|
Checks if the command can be executed by checking all the predicates
inside the :attr:`~Command.checks` attribute. This also checks whether the
command is disabled.
.. versionchanged:: 1.3
Checks whether the command is disabled or not
Parameters
----------
ctx: :class:`.Context`
The ctx of the command currently being invoked.
Raises
------
:class:`CommandError`
Any command error that was raised during a check call will be propagated
by this function.
Returns
-------
:class:`bool`
A boolean indicating if the command can be invoked.
"""
if not self.enabled:
raise DisabledCommand(f"{self.name} command is disabled")
original = ctx.command
ctx.command = self
try:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.qualified_name} failed."
)
cog = self.cog
if cog is not None:
local_check = Cog._get_overridden_method(cog.cog_check)
if local_check is not None:
ret = await nextcord.utils.maybe_coroutine(local_check, ctx)
if not ret:
return False
predicates = self.checks
if not predicates:
# since we have no checks, then we just return True.
return True
return await nextcord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
finally:
ctx.command = original
CoroFunc = Callable[..., Coro[Any]]
The provided code snippet includes necessary dependencies for implementing the `after_invoke` function. Write a Python function `def after_invoke(coro) -> Callable[[T], T]` to solve the following problem:
A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4
Here is the function:
def after_invoke(coro) -> Callable[[T], T]:
"""A decorator that registers a coroutine as a post-invoke hook.
This allows you to refer to one after invoke hook for several commands that
do not have to be within the same cog.
.. versionadded:: 1.4
"""
def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]:
if isinstance(func, Command):
func.after_invoke(coro)
else:
func.__after_invoke__ = coro
return func
return decorator # type: ignore | A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog. .. versionadded:: 1.4 |
160,909 | from __future__ import annotations
import inspect
import re
import sys
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Pattern,
Set,
Tuple,
Type,
Union,
)
from nextcord.utils import MISSING, maybe_coroutine, resolve_annotation
from .converter import run_converters
from .errors import (
BadFlagArgument,
CommandError,
MissingFlagArgument,
MissingRequiredFlag,
TooManyFlags,
)
from .view import StringView
def validate_flag_name(name: str, forbidden: Set[str]):
if not name:
raise ValueError("flag names should not be empty")
for ch in name:
if ch.isspace():
raise ValueError(f"flag name {name!r} cannot have spaces")
if ch == "\\":
raise ValueError(f"flag name {name!r} cannot have backslashes")
if ch in forbidden:
raise ValueError(f"flag name {name!r} cannot have any of {forbidden!r} within them") | null |
160,910 | from __future__ import annotations
import inspect
import re
import sys
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Pattern,
Set,
Tuple,
Type,
Union,
)
from nextcord.utils import MISSING, maybe_coroutine, resolve_annotation
from .converter import run_converters
from .errors import (
BadFlagArgument,
CommandError,
MissingFlagArgument,
MissingRequiredFlag,
TooManyFlags,
)
from .view import StringView
class Flag:
"""Represents a flag parameter for :class:`FlagConverter`.
The :func:`~nextcord.ext.commands.flag` function helps
create these flag objects, but it is not necessary to
do so. These cannot be constructed manually.
Attributes
----------
name: :class:`str`
The name of the flag.
aliases: List[:class:`str`]
The aliases of the flag name.
attribute: :class:`str`
The attribute in the class that corresponds to this flag.
default: Any
The default value of the flag, if available.
annotation: Any
The underlying evaluated annotation of the flag.
max_args: :class:`int`
The maximum number of arguments the flag can accept.
A negative value indicates an unlimited amount of arguments.
override: :class:`bool`
Whether multiple given values overrides the previous value.
"""
name: str = MISSING
aliases: List[str] = field(default_factory=list)
attribute: str = MISSING
annotation: Any = MISSING
default: Any = MISSING
max_args: int = MISSING
override: bool = MISSING
cast_to_dict: bool = False
def required(self) -> bool:
""":class:`bool`: Whether the flag is required.
A required flag has no default value.
"""
return self.default is MISSING
def flag(
*,
name: str = MISSING,
aliases: List[str] = MISSING,
default: Any = MISSING,
max_args: int = MISSING,
override: bool = MISSING,
) -> Any:
"""Override default functionality and parameters of the underlying :class:`FlagConverter`
class attributes.
Parameters
----------
name: :class:`str`
The flag name. If not given, defaults to the attribute name.
aliases: List[:class:`str`]
Aliases to the flag name. If not given no aliases are set.
default: Any
The default parameter. This could be either a value or a callable that takes
:class:`Context` as its sole parameter. If not given then it defaults to
the default value given to the attribute.
max_args: :class:`int`
The maximum number of arguments the flag can accept.
A negative value indicates an unlimited amount of arguments.
The default value depends on the annotation given.
override: :class:`bool`
Whether multiple given values overrides the previous value. The default
value depends on the annotation given.
"""
return Flag(name=name, aliases=aliases, default=default, max_args=max_args, override=override)
MISSING: Any = _MissingSentinel()
def resolve_annotation(
annotation: Any,
globalns: Dict[str, Any],
localns: Optional[Dict[str, Any]],
cache: Optional[Dict[str, Any]],
) -> Any:
if annotation is None:
return type(None)
if isinstance(annotation, str):
annotation = ForwardRef(annotation)
locals = globalns if localns is None else localns
if cache is None:
cache = {}
return evaluate_annotation(annotation, globalns, locals, cache)
def get_flags(
namespace: Dict[str, Any], globals: Dict[str, Any], locals: Dict[str, Any]
) -> Dict[str, Flag]:
annotations = namespace.get("__annotations__", {})
case_insensitive = namespace["__commands_flag_case_insensitive__"]
flags: Dict[str, Flag] = {}
cache: Dict[str, Any] = {}
names: Set[str] = set()
for name, annotation in annotations.items():
flag = namespace.pop(name, MISSING)
if isinstance(flag, Flag):
if flag.annotation is MISSING:
flag.annotation = annotation
else:
flag = Flag(name=name, annotation=annotation, default=flag)
flag.attribute = name
if flag.name is MISSING:
flag.name = name
annotation = flag.annotation = resolve_annotation(flag.annotation, globals, locals, cache)
if (
flag.default is MISSING
and hasattr(annotation, "__commands_is_flag__")
and annotation._can_be_constructible()
):
flag.default = annotation._construct_default
if flag.aliases is MISSING:
flag.aliases = []
# Add sensible defaults based off of the type annotation
# <type> -> (max_args=1)
# List[str] -> (max_args=-1)
# Tuple[int, ...] -> (max_args=1)
# Dict[K, V] -> (max_args=-1, override=True)
# Union[str, int] -> (max_args=1)
# Optional[str] -> (default=None, max_args=1)
try:
origin = annotation.__origin__
except AttributeError:
# A regular type hint
if flag.max_args is MISSING:
flag.max_args = 1
else:
if origin is Union:
# typing.Union
if flag.max_args is MISSING:
flag.max_args = 1
if annotation.__args__[-1] is type(None) and flag.default is MISSING:
# typing.Optional
flag.default = None
elif origin is tuple:
# typing.Tuple
# tuple parsing is e.g. `flag: peter 20`
# for Tuple[str, int] would give you flag: ('peter', 20)
if flag.max_args is MISSING:
flag.max_args = 1
elif origin is list:
# typing.List
if flag.max_args is MISSING:
flag.max_args = -1
elif origin is dict:
# typing.Dict[K, V] is equivalent to typing.List[typing.Tuple[K, V]]
flag.cast_to_dict = True
if flag.max_args is MISSING:
flag.max_args = -1
if flag.override is MISSING:
flag.override = True
elif origin is Literal:
if flag.max_args is MISSING:
flag.max_args = 1
else:
raise TypeError(
f"Unsupported typing annotation {annotation!r} for {flag.name!r} flag"
)
if flag.override is MISSING:
flag.override = False
# Validate flag names are unique
name = flag.name.casefold() if case_insensitive else flag.name
if name in names:
raise TypeError(f"{flag.name!r} flag conflicts with previous flag or alias.")
names.add(name)
for alias in flag.aliases:
# Validate alias is unique
alias = alias.casefold() if case_insensitive else alias
if alias in names:
raise TypeError(
f"{flag.name!r} flag alias {alias!r} conflicts with previous flag or alias."
)
names.add(alias)
flags[flag.name] = flag
return flags | null |
160,911 | from __future__ import annotations
import inspect
import re
import sys
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Pattern,
Set,
Tuple,
Type,
Union,
)
from nextcord.utils import MISSING, maybe_coroutine, resolve_annotation
from .converter import run_converters
from .errors import (
BadFlagArgument,
CommandError,
MissingFlagArgument,
MissingRequiredFlag,
TooManyFlags,
)
from .view import StringView
class Flag:
"""Represents a flag parameter for :class:`FlagConverter`.
The :func:`~nextcord.ext.commands.flag` function helps
create these flag objects, but it is not necessary to
do so. These cannot be constructed manually.
Attributes
----------
name: :class:`str`
The name of the flag.
aliases: List[:class:`str`]
The aliases of the flag name.
attribute: :class:`str`
The attribute in the class that corresponds to this flag.
default: Any
The default value of the flag, if available.
annotation: Any
The underlying evaluated annotation of the flag.
max_args: :class:`int`
The maximum number of arguments the flag can accept.
A negative value indicates an unlimited amount of arguments.
override: :class:`bool`
Whether multiple given values overrides the previous value.
"""
name: str = MISSING
aliases: List[str] = field(default_factory=list)
attribute: str = MISSING
annotation: Any = MISSING
default: Any = MISSING
max_args: int = MISSING
override: bool = MISSING
cast_to_dict: bool = False
def required(self) -> bool:
""":class:`bool`: Whether the flag is required.
A required flag has no default value.
"""
return self.default is MISSING
async def tuple_convert_all(
ctx: Context, argument: str, flag: Flag, converter: Any
) -> Tuple[Any, ...]:
view = StringView(argument)
results = []
param: inspect.Parameter = ctx.current_parameter # type: ignore
while not view.eof:
view.skip_ws()
if view.eof:
break
word = view.get_quoted_word()
if word is None:
break
try:
converted = await run_converters(ctx, converter, word, param)
except CommandError:
raise
except Exception as e:
raise BadFlagArgument(flag) from e
else:
results.append(converted)
return tuple(results)
async def tuple_convert_flag(
ctx: Context, argument: str, flag: Flag, converters: Any
) -> Tuple[Any, ...]:
view = StringView(argument)
results = []
param: inspect.Parameter = ctx.current_parameter # type: ignore
for converter in converters:
view.skip_ws()
if view.eof:
break
word = view.get_quoted_word()
if word is None:
break
try:
converted = await run_converters(ctx, converter, word, param)
except CommandError:
raise
except Exception as e:
raise BadFlagArgument(flag) from e
else:
results.append(converted)
if len(results) != len(converters):
raise BadFlagArgument(flag)
return tuple(results)
async def run_converters(ctx: Context, converter, argument: str, param: inspect.Parameter):
"""|coro|
Runs converters for a given converter, argument, and parameter.
This function does the same work that the library does under the hood.
.. versionadded:: 2.0
Parameters
----------
ctx: :class:`Context`
The invocation context to run the converters under.
converter: Any
The converter to run, this corresponds to the annotation in the function.
argument: :class:`str`
The argument to convert to.
param: :class:`inspect.Parameter`
The parameter being converted. This is mainly for error reporting.
Raises
------
CommandError
The converter failed to convert.
Returns
-------
Any
The resulting conversion.
"""
origin = getattr(converter, "__origin__", None)
if origin is Union:
errors = []
_NoneType = type(None)
union_args = converter.__args__
for conv in union_args:
# if we got to this part in the code, then the previous conversions have failed
# so we should just undo the view, return the default, and allow parsing to continue
# with the other parameters
if conv is _NoneType and param.kind != param.VAR_POSITIONAL:
ctx.view.undo()
return None if param.default is param.empty else param.default
try:
value = await run_converters(ctx, conv, argument, param)
except CommandError as exc:
errors.append(exc)
else:
return value
# if we're here, then we failed all the converters
raise BadUnionArgument(param, union_args, errors)
if origin is Literal:
errors = []
conversions = {}
literal_args = converter.__args__
for literal in literal_args:
literal_type = type(literal)
try:
value = conversions[literal_type]
except KeyError:
try:
value = await _actual_conversion(ctx, literal_type, argument, param)
except CommandError as exc:
errors.append(exc)
conversions[literal_type] = object()
continue
else:
conversions[literal_type] = value
if value == literal:
return value
# if we're here, then we failed to match all the literals
raise BadLiteralArgument(param, literal_args, errors)
# This must be the last if-clause in the chain of origin checking
# Nearly every type is a generic type within the typing library
# So care must be taken to make sure a more specialised origin handle
# isn't overwritten by the widest if clause
if origin is not None and is_generic_type(converter):
converter = origin
return await _actual_conversion(ctx, converter, argument, param)
class CommandError(DiscordException):
r"""The base exception type for all command related errors.
This inherits from :exc:`nextcord.DiscordException`.
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from :class:`.Bot`\, :func:`.on_command_error`.
"""
def __init__(self, message: Optional[str] = None, *args: Any) -> None:
if message is not None:
# clean-up @everyone and @here mentions
m = message.replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere")
super().__init__(m, *args)
else:
super().__init__(*args)
class BadFlagArgument(FlagError):
"""An exception raised when a flag failed to convert a value.
This inherits from :exc:`FlagError`
.. versionadded:: 2.0
Attributes
----------
flag: :class:`~nextcord.ext.commands.Flag`
The flag that failed to convert.
"""
def __init__(self, flag: Flag) -> None:
self.flag: Flag = flag
try:
name = flag.annotation.__name__
except AttributeError:
name = flag.annotation.__class__.__name__
super().__init__(f"Could not convert to {name!r} for flag {flag.name!r}")
async def convert_flag(ctx, argument: str, flag: Flag, annotation: Any = None) -> Any:
param: inspect.Parameter = ctx.current_parameter
annotation = annotation or flag.annotation
try:
origin = annotation.__origin__
except AttributeError:
pass
else:
if origin is tuple:
if annotation.__args__[-1] is Ellipsis:
return await tuple_convert_all(ctx, argument, flag, annotation.__args__[0])
return await tuple_convert_flag(ctx, argument, flag, annotation.__args__)
if origin is list:
# typing.List[x] # noqa: ERA001
annotation = annotation.__args__[0]
return await convert_flag(ctx, argument, flag, annotation)
if origin is Union and annotation.__args__[-1] is type(None):
# typing.Optional[x] # noqa: ERA001
annotation = Union[annotation.__args__[:-1]] # type: ignore
return await run_converters(ctx, annotation, argument, param)
if origin is dict:
# typing.Dict[K, V] -> typing.Tuple[K, V]
return await tuple_convert_flag(ctx, argument, flag, annotation.__args__)
try:
return await run_converters(ctx, annotation, argument, param)
except CommandError:
raise
except Exception as e:
raise BadFlagArgument(flag) from e | null |
160,912 | from __future__ import annotations
import asyncio
import collections
import collections.abc
import contextlib
import copy
import importlib.util
import inspect
import os
import sys
import traceback
import types
import warnings
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
import nextcord
from . import errors
from .cog import Cog
from .context import Context
from .core import GroupMixin
from .help import DefaultHelpCommand, HelpCommand
from .view import StringView
def when_mentioned(bot: Union[Bot, AutoShardedBot], _msg: Message) -> List[str]:
"""A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the :attr:`.Bot.command_prefix` attribute.
"""
# bot.user will never be None when this is called
return [f"<@{bot.user.id}> ", f"<@!{bot.user.id}> "] # type: ignore
class Bot(BotBase, nextcord.Client):
"""Represents a discord bot.
This class is a subclass of :class:`nextcord.Client` and as a result
anything that you can do with a :class:`nextcord.Client` you can do with
this bot.
This class also subclasses :class:`.GroupMixin` to provide the functionality
to manage commands.
Attributes
----------
command_prefix
The command prefix is what the message content must contain initially
to have a command invoked. This prefix could either be a string to
indicate what the prefix should be, or a callable that takes in the bot
as its first parameter and :class:`nextcord.Message` as its second
parameter and returns the prefix. This is to facilitate "dynamic"
command prefixes. This callable can be either a regular function or
a coroutine.
An empty string as the prefix always matches, enabling prefix-less
command invocation. While this may be useful in DMs it should be avoided
in servers, as it's likely to cause performance issues and unintended
command invocations.
The command prefix could also be an iterable of strings indicating that
multiple checks for the prefix should be used and the first one to
match will be the invocation prefix. You can get this prefix via
:attr:`.Context.prefix`.
.. note::
When passing multiple prefixes be careful to not pass a prefix
that matches a longer prefix occurring later in the sequence. For
example, if the command prefix is ``('!', '!?')`` the ``'!?'``
prefix will never be matched to any message as the previous one
matches messages starting with ``!?``. This is especially important
when passing an empty string, it should always be last as no prefix
after it will be matched.
case_insensitive: :class:`bool`
Whether the commands should be case insensitive. Defaults to ``False``. This
attribute does not carry over to groups. You must set it to every group if
you require group commands to be case insensitive as well.
description: :class:`str`
The content prefixed into the default help message.
help_command: Optional[:class:`.HelpCommand`]
The help command implementation to use. This can be dynamically
set at runtime. To remove the help command pass ``None``. For more
information on implementing a help command, see :ref:`ext_commands_help_command`.
owner_id: Optional[:class:`int`]
The user ID that owns the bot. If this is not set and is then queried via
:meth:`.is_owner` then it is fetched automatically using
:meth:`~.Bot.application_info`.
owner_ids: Optional[Collection[:class:`int`]]
The user IDs that owns the bot. This is similar to :attr:`owner_id`.
If this is not set and the application is team based, then it is
fetched automatically using :meth:`~.Bot.application_info`.
For performance reasons it is recommended to use a :class:`set`
for the collection. You cannot set both ``owner_id`` and ``owner_ids``.
.. versionadded:: 1.3
strip_after_prefix: :class:`bool`
Whether to strip whitespace characters after encountering the command
prefix. This allows for ``! hello`` and ``!hello`` to both work if
the ``command_prefix`` is set to ``!``. Defaults to ``False``.
.. versionadded:: 1.7
"""
def __init__(
self,
command_prefix: Union[
_NonCallablePrefix,
Callable[
[Union[Bot, AutoShardedBot], Message],
Union[Awaitable[_NonCallablePrefix], _NonCallablePrefix],
],
] = (),
help_command: Optional[HelpCommand] = MISSING,
description: Optional[str] = None,
*,
max_messages: Optional[int] = 1000,
connector: Optional[aiohttp.BaseConnector] = None,
proxy: Optional[str] = None,
proxy_auth: Optional[aiohttp.BasicAuth] = None,
shard_id: Optional[int] = None,
shard_count: Optional[int] = None,
application_id: Optional[int] = None,
intents: nextcord.Intents = nextcord.Intents.default(),
member_cache_flags: MemberCacheFlags = MISSING,
chunk_guilds_at_startup: bool = MISSING,
status: Optional[Status] = None,
activity: Optional[BaseActivity] = None,
allowed_mentions: Optional[AllowedMentions] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
assume_unsync_clock: bool = True,
enable_debug_events: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None,
lazy_load_commands: bool = True,
rollout_associate_known: bool = True,
rollout_delete_unknown: bool = True,
rollout_register_new: bool = True,
rollout_update_known: bool = True,
rollout_all_guilds: bool = False,
default_guild_ids: Optional[List[int]] = None,
owner_id: Optional[int] = None,
owner_ids: Optional[Iterable[int]] = None,
strip_after_prefix: bool = False,
case_insensitive: bool = False,
) -> None:
nextcord.Client.__init__(
self,
max_messages=max_messages,
connector=connector,
proxy=proxy,
proxy_auth=proxy_auth,
shard_id=shard_id,
shard_count=shard_count,
application_id=application_id,
intents=intents,
member_cache_flags=member_cache_flags,
chunk_guilds_at_startup=chunk_guilds_at_startup,
status=status,
activity=activity,
allowed_mentions=allowed_mentions,
heartbeat_timeout=heartbeat_timeout,
guild_ready_timeout=guild_ready_timeout,
assume_unsync_clock=assume_unsync_clock,
enable_debug_events=enable_debug_events,
loop=loop,
lazy_load_commands=lazy_load_commands,
rollout_associate_known=rollout_associate_known,
rollout_delete_unknown=rollout_delete_unknown,
rollout_register_new=rollout_register_new,
rollout_update_known=rollout_update_known,
rollout_all_guilds=rollout_all_guilds,
default_guild_ids=default_guild_ids,
)
BotBase.__init__(
self,
command_prefix=command_prefix,
help_command=help_command,
description=description,
owner_id=owner_id,
owner_ids=owner_ids,
strip_after_prefix=strip_after_prefix,
case_insensitive=case_insensitive,
)
class AutoShardedBot(BotBase, nextcord.AutoShardedClient):
"""This is similar to :class:`.Bot` except that it is inherited from
:class:`nextcord.AutoShardedClient` instead.
"""
def __init__(
self,
command_prefix: Union[
_NonCallablePrefix,
Callable[
[Union[Bot, AutoShardedBot], Message],
Union[Awaitable[_NonCallablePrefix], _NonCallablePrefix],
],
] = (),
help_command: Optional[HelpCommand] = MISSING,
description: Optional[str] = None,
*,
max_messages: Optional[int] = 1000,
connector: Optional[aiohttp.BaseConnector] = None,
proxy: Optional[str] = None,
proxy_auth: Optional[aiohttp.BasicAuth] = None,
shard_id: Optional[int] = None,
shard_count: Optional[int] = None,
shard_ids: Optional[list[int]] = None,
application_id: Optional[int] = None,
intents: nextcord.Intents = nextcord.Intents.default(),
member_cache_flags: MemberCacheFlags = MISSING,
chunk_guilds_at_startup: bool = MISSING,
status: Optional[Status] = None,
activity: Optional[BaseActivity] = None,
allowed_mentions: Optional[AllowedMentions] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
assume_unsync_clock: bool = True,
enable_debug_events: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None,
lazy_load_commands: bool = True,
rollout_associate_known: bool = True,
rollout_delete_unknown: bool = True,
rollout_register_new: bool = True,
rollout_update_known: bool = True,
rollout_all_guilds: bool = False,
default_guild_ids: Optional[List[int]] = None,
owner_id: Optional[int] = None,
owner_ids: Optional[Iterable[int]] = None,
strip_after_prefix: bool = False,
case_insensitive: bool = False,
) -> None:
nextcord.AutoShardedClient.__init__(
self,
max_messages=max_messages,
connector=connector,
proxy=proxy,
proxy_auth=proxy_auth,
shard_id=shard_id,
shard_count=shard_count,
shard_ids=shard_ids,
application_id=application_id,
intents=intents,
member_cache_flags=member_cache_flags,
chunk_guilds_at_startup=chunk_guilds_at_startup,
status=status,
activity=activity,
allowed_mentions=allowed_mentions,
heartbeat_timeout=heartbeat_timeout,
guild_ready_timeout=guild_ready_timeout,
assume_unsync_clock=assume_unsync_clock,
enable_debug_events=enable_debug_events,
loop=loop,
lazy_load_commands=lazy_load_commands,
rollout_associate_known=rollout_associate_known,
rollout_delete_unknown=rollout_delete_unknown,
rollout_register_new=rollout_register_new,
rollout_update_known=rollout_update_known,
rollout_all_guilds=rollout_all_guilds,
default_guild_ids=default_guild_ids,
)
BotBase.__init__(
self,
command_prefix=command_prefix,
help_command=help_command,
description=description,
owner_id=owner_id,
owner_ids=owner_ids,
strip_after_prefix=strip_after_prefix,
case_insensitive=case_insensitive,
)
class Message(Hashable):
r"""Represents a message from Discord.
.. container:: operations
.. describe:: x == y
Checks if two messages are equal.
.. describe:: x != y
Checks if two messages are not equal.
.. describe:: hash(x)
Returns the message's hash.
Attributes
----------
tts: :class:`bool`
Specifies if the message was done with text-to-speech.
This can only be accurately received in :func:`on_message` due to
a discord limitation.
type: :class:`MessageType`
The type of message. In most cases this should not be checked, but it is helpful
in cases where it might be a system message for :attr:`system_content`.
author: Union[:class:`Member`, :class:`abc.User`]
A :class:`Member` that sent the message. If :attr:`channel` is a
private channel or the user has the left the guild, then it is a :class:`User` instead.
content: :class:`str`
The actual contents of the message.
nonce: Optional[Union[:class:`str`, :class:`int`]]
The value used by the discord guild and the client to verify that the message is successfully sent.
This is not stored long term within Discord's servers and is only used ephemerally.
embeds: List[:class:`Embed`]
A list of embeds the message has.
channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`]
The :class:`TextChannel` or :class:`Thread` that the message was sent from.
Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message.
reference: Optional[:class:`~nextcord.MessageReference`]
The message that this message references. This is only applicable to messages of
type :attr:`MessageType.pins_add`, crossposted messages created by a
followed channel integration, or message replies.
.. versionadded:: 1.5
mention_everyone: :class:`bool`
Specifies if the message mentions everyone.
.. note::
This does not check if the ``@everyone`` or the ``@here`` text is in the message itself.
Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message
**and** it did end up mentioning.
mentions: List[:class:`abc.User`]
A list of :class:`Member` that were mentioned. If the message is in a private message
then the list will be of :class:`User` instead. For messages that are not of type
:attr:`MessageType.default`\, this array can be used to aid in system messages.
For more information, see :attr:`system_content`.
.. warning::
The order of the mentions list is not in any particular order so you should
not rely on it. This is a Discord limitation, not one with the library.
channel_mentions: List[:class:`abc.GuildChannel`]
A list of :class:`abc.GuildChannel` that were mentioned. If the message is in a private message
then the list is always empty.
role_mentions: List[:class:`Role`]
A list of :class:`Role` that were mentioned. If the message is in a private message
then the list is always empty.
id: :class:`int`
The message ID.
webhook_id: Optional[:class:`int`]
If this message was sent by a webhook, then this is the webhook ID's that sent this
message.
attachments: List[:class:`Attachment`]
A list of attachments given to a message.
pinned: :class:`bool`
Specifies if the message is currently pinned.
flags: :class:`MessageFlags`
Extra features of the message.
.. versionadded:: 1.3
reactions : List[:class:`Reaction`]
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
activity: Optional[:class:`dict`]
The activity associated with this message. Sent with Rich-Presence related messages that for
example, request joining, spectating, or listening to or with another member.
It is a dictionary with the following optional keys:
- ``type``: An integer denoting the type of message activity being requested.
- ``party_id``: The party ID associated with the party.
application: Optional[:class:`dict`]
The rich presence enabled application associated with this message.
It is a dictionary with the following keys:
- ``id``: A string representing the application's ID.
- ``name``: A string representing the application's name.
- ``description``: A string representing the application's description.
- ``icon``: A string representing the icon ID of the application.
- ``cover_image``: A string representing the embed's image asset ID.
stickers: List[:class:`StickerItem`]
A list of sticker items given to the message.
.. versionadded:: 1.6
components: List[:class:`Component`]
A list of components in the message.
.. versionadded:: 2.0
guild: Optional[:class:`Guild`]
The guild that the message belongs to, if applicable.
interaction: Optional[:class:`MessageInteraction`]
The interaction data of a message, if applicable.
"""
__slots__ = (
"_state",
"_edited_timestamp",
"_cs_channel_mentions",
"_cs_raw_mentions",
"_cs_clean_content",
"_cs_raw_channel_mentions",
"_cs_raw_role_mentions",
"_cs_system_content",
"tts",
"content",
"channel",
"webhook_id",
"mention_everyone",
"embeds",
"id",
"interaction",
"mentions",
"author",
"attachments",
"nonce",
"pinned",
"role_mentions",
"type",
"flags",
"reactions",
"reference",
"application",
"activity",
"stickers",
"components",
"_background_tasks",
"guild",
)
if TYPE_CHECKING:
_HANDLERS: ClassVar[List[Tuple[str, Callable[..., None]]]]
_CACHED_SLOTS: ClassVar[List[str]]
guild: Optional[Guild]
reference: Optional[MessageReference]
mentions: List[Union[User, Member]]
author: Union[User, Member]
role_mentions: List[Role]
def __init__(
self,
*,
state: ConnectionState,
channel: MessageableChannel,
data: MessagePayload,
) -> None:
self._state: ConnectionState = state
self.id: int = int(data["id"])
self.webhook_id: Optional[int] = utils.get_as_snowflake(data, "webhook_id")
self.reactions: List[Reaction] = [
Reaction(message=self, data=d) for d in data.get("reactions", [])
]
self.attachments: List[Attachment] = [
Attachment(data=a, state=self._state) for a in data["attachments"]
]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data["embeds"]]
self.application: Optional[MessageApplicationPayload] = data.get("application")
self.activity: Optional[MessageActivityPayload] = data.get("activity")
self.channel: MessageableChannel = channel
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(
data["edited_timestamp"]
)
self.type: MessageType = try_enum(MessageType, data["type"])
self.pinned: bool = data["pinned"]
self.flags: MessageFlags = MessageFlags._from_value(data.get("flags", 0))
self.mention_everyone: bool = data["mention_everyone"]
self.tts: bool = data["tts"]
self.content: str = data["content"]
self.nonce: Optional[Union[int, str]] = data.get("nonce")
self.stickers: List[StickerItem] = [
StickerItem(data=d, state=state) for d in data.get("sticker_items", [])
]
self.components: List[Component] = [
_component_factory(d) for d in data.get("components", [])
]
self._background_tasks: Set[asyncio.Task[None]] = set()
try:
# if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild # type: ignore
except AttributeError:
if getattr(channel, "type", None) not in (ChannelType.group, ChannelType.private):
self.guild = state._get_guild(utils.get_as_snowflake(data, "guild_id"))
else:
self.guild = None
if (
(thread_data := data.get("thread"))
and not self.thread
and isinstance(self.guild, Guild)
):
self.guild._store_thread(thread_data)
try:
ref = data["message_reference"]
except KeyError:
self.reference = None
else:
self.reference = ref = MessageReference.with_state(state, ref)
try:
resolved = data["referenced_message"]
except KeyError:
pass
else:
if resolved is None:
ref.resolved = DeletedReferencedMessage(ref)
else:
# Right now the channel IDs match but maybe in the future they won't.
if ref.channel_id == channel.id:
chan = channel
else:
chan, _ = state._get_guild_channel(resolved)
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore
for handler in ("author", "member", "mentions", "mention_roles"):
try:
getattr(self, f"_handle_{handler}")(data[handler])
except KeyError:
continue
self.interaction: Optional[MessageInteraction] = (
MessageInteraction(data=data["interaction"], guild=self.guild, state=self._state)
if "interaction" in data
else None
)
def __repr__(self) -> str:
name = self.__class__.__name__
return f"<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>"
def _try_patch(self, data, key, transform=None) -> None:
try:
value = data[key]
except KeyError:
pass
else:
if transform is None:
setattr(self, key, value)
else:
setattr(self, key, transform(value))
def _add_reaction(self, data, emoji: Emoji | PartialEmoji | str, user_id) -> Reaction:
finder: Callable[[Reaction], bool] = lambda r: r.emoji == emoji
reaction = utils.find(finder, self.reactions)
is_me = data["me"] = user_id == self._state.self_id
if reaction is None:
reaction = Reaction(message=self, data=data, emoji=emoji)
self.reactions.append(reaction)
else:
reaction.count += 1
if is_me:
reaction.me = is_me
return reaction
def _remove_reaction(
self, data: ReactionPayload, emoji: EmojiInputType, user_id: int
) -> Reaction:
reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)
if reaction is None:
# already removed?
raise ValueError("Emoji already removed?")
# if reaction isn't in the list, we crash. This means discord
# sent bad data, or we stored improperly
reaction.count -= 1
if user_id == self._state.self_id:
reaction.me = False
if reaction.count == 0:
# this raises ValueError if something went wrong as well.
self.reactions.remove(reaction)
return reaction
def _clear_emoji(self, emoji) -> Optional[Reaction]:
to_check = str(emoji)
for index, reaction in enumerate(self.reactions): # noqa: B007
if str(reaction.emoji) == to_check:
break
else:
# didn't find anything so just return
return None
del self.reactions[index]
return reaction
def _update(self, data) -> None:
# In an update scheme, 'author' key has to be handled before 'member'
# otherwise they overwrite each other which is undesirable.
# Since there's no good way to do this we have to iterate over every
# handler rather than iterating over the keys which is a little slower
for key, handler in self._HANDLERS:
try:
value = data[key]
except KeyError:
continue
else:
handler(self, value)
# clear the cached properties
for attr in self._CACHED_SLOTS:
with contextlib.suppress(AttributeError):
delattr(self, attr)
def _handle_edited_timestamp(self, value: str) -> None:
self._edited_timestamp = utils.parse_time(value)
def _handle_pinned(self, value: bool) -> None:
self.pinned = value
def _handle_flags(self, value: int) -> None:
self.flags = MessageFlags._from_value(value)
def _handle_application(self, value: MessageApplicationPayload) -> None:
self.application = value
def _handle_activity(self, value: MessageActivityPayload) -> None:
self.activity = value
def _handle_mention_everyone(self, value: bool) -> None:
self.mention_everyone = value
def _handle_tts(self, value: bool) -> None:
self.tts = value
def _handle_type(self, value: int) -> None:
self.type = try_enum(MessageType, value)
def _handle_content(self, value: str) -> None:
self.content = value
def _handle_attachments(self, value: List[AttachmentPayload]) -> None:
self.attachments = [Attachment(data=a, state=self._state) for a in value]
def _handle_embeds(self, value: List[EmbedPayload]) -> None:
self.embeds = [Embed.from_dict(data) for data in value]
def _handle_nonce(self, value: Union[str, int]) -> None:
self.nonce = value
def _handle_author(self, author: UserPayload) -> None:
self.author = self._state.store_user(author)
if isinstance(self.guild, Guild):
found = self.guild.get_member(self.author.id)
if found is not None:
self.author = found
def _handle_member(self, member: MemberPayload) -> None:
# The gateway now gives us full Member objects sometimes with the following keys
# deaf, mute, joined_at, roles
# For the sake of performance I'm going to assume that the only
# field that needs *updating* would be the joined_at field.
# If there is no Member object (for some strange reason), then we can upgrade
# ourselves to a more "partial" member object.
author = self.author
try:
# Update member reference
author._update_from_message(member) # type: ignore
except AttributeError:
# It's a user here
# TODO: consider adding to cache here
self.author = Member._from_message(message=self, data=member)
def _handle_mentions(self, mentions: List[UserWithMemberPayload]) -> None:
self.mentions = r = []
guild = self.guild
state = self._state
if not isinstance(guild, Guild):
self.mentions = [state.store_user(m) for m in mentions]
return
for mention in filter(None, mentions):
id_search = int(mention["id"])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
else:
r.append(Member._try_upgrade(data=mention, guild=guild, state=state))
def _handle_mention_roles(self, role_mentions: List[int]) -> None:
self.role_mentions = []
if isinstance(self.guild, Guild):
for role_id in map(int, role_mentions):
role = self.guild.get_role(role_id)
if role is not None:
self.role_mentions.append(role)
def _handle_components(self, components: List[ComponentPayload]) -> None:
self.components = [_component_factory(d) for d in components]
def _handle_thread(self, thread: Optional[ThreadPayload]) -> None:
if thread:
self.guild._store_thread(thread) # type: ignore
def _rebind_cached_references(
self, new_guild: Guild, new_channel: Union[TextChannel, Thread]
) -> None:
self.guild = new_guild
self.channel = new_channel
def raw_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of user IDs matched with
the syntax of ``<@user_id>`` in the message content.
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return utils.parse_raw_mentions(self.content)
def raw_channel_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of channel IDs matched with
the syntax of ``<#channel_id>`` in the message content.
"""
return utils.parse_raw_channel_mentions(self.content)
def raw_role_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of role IDs matched with
the syntax of ``<@&role_id>`` in the message content.
"""
return utils.parse_raw_role_mentions(self.content)
def channel_mentions(self) -> List[GuildChannel]:
if self.guild is None:
return []
it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions))
return utils.unique(it)
def clean_content(self) -> str:
""":class:`str`: A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
into the way the client shows it. e.g. ``<#id>`` will transform
into ``#name``.
This will also transform @everyone and @here mentions into
non-mentions.
.. note::
This *does not* affect markdown. If you want to escape
or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown`
respectively, along with this function.
"""
transformations = {
re.escape(f"<#{channel.id}>"): "#" + channel.name for channel in self.channel_mentions
}
mention_transforms = {
re.escape(f"<@{member.id}>"): "@" + member.display_name for member in self.mentions
}
# add the <@!user_id> cases as well..
second_mention_transforms = {
re.escape(f"<@!{member.id}>"): "@" + member.display_name for member in self.mentions
}
transformations.update(mention_transforms)
transformations.update(second_mention_transforms)
if self.guild is not None:
role_transforms = {
re.escape(f"<@&{role.id}>"): "@" + role.name for role in self.role_mentions
}
transformations.update(role_transforms)
def repl(obj):
return transformations.get(re.escape(obj.group(0)), "")
pattern = re.compile("|".join(transformations.keys()))
result = pattern.sub(repl, self.content)
return escape_mentions(result)
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The message's creation time in UTC."""
return utils.snowflake_time(self.id)
def edited_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: An aware UTC datetime object containing the edited time of the message."""
return self._edited_timestamp
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this message."""
guild_id = getattr(self.guild, "id", "@me")
return f"https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}"
def thread(self) -> Optional[Thread]:
"""Optional[:class:`Thread`]: The thread started from this message. None if no thread was started."""
if not isinstance(self.guild, Guild):
return None
return self.guild.get_thread(self.id)
def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API
in response to something.
.. versionadded:: 1.3
"""
return self.type not in (
MessageType.default,
MessageType.reply,
MessageType.chat_input_command,
MessageType.context_menu_command,
MessageType.thread_starter_message,
)
def system_content(self):
r""":class:`str`: A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default` and :attr:`MessageType.reply`\,
this just returns the regular :attr:`Message.content`. Otherwise this
returns an English message denoting the contents of the system message.
"""
if self.type is MessageType.default:
return self.content
if self.type is MessageType.recipient_add:
if self.channel.type is ChannelType.group:
return f"{self.author.name} added {self.mentions[0].name} to the group."
return f"{self.author.name} added {self.mentions[0].name} to the thread."
if self.type is MessageType.recipient_remove:
if self.channel.type is ChannelType.group:
return f"{self.author.name} removed {self.mentions[0].name} from the group."
return f"{self.author.name} removed {self.mentions[0].name} from the thread."
if self.type is MessageType.channel_name_change:
return f"{self.author.name} changed the channel name: **{self.content}**"
if self.type is MessageType.channel_icon_change:
return f"{self.author.name} changed the channel icon."
if self.type is MessageType.pins_add:
return f"{self.author.name} pinned a message to this channel."
if self.type is MessageType.new_member:
formats = [
"{0} joined the party.",
"{0} is here.",
"Welcome, {0}. We hope you brought pizza.",
"A wild {0} appeared.",
"{0} just landed.",
"{0} just slid into the server.",
"{0} just showed up!",
"Welcome {0}. Say hi!",
"{0} hopped into the server.",
"Everyone welcome {0}!",
"Glad you're here, {0}.",
"Good to see you, {0}.",
"Yay you made it, {0}!",
]
created_at_ms = int(self.created_at.timestamp() * 1000)
return formats[created_at_ms % len(formats)].format(self.author.name)
if self.type is MessageType.premium_guild_subscription:
if not self.content:
return f"{self.author.name} just boosted the server!"
return f"{self.author.name} just boosted the server **{self.content}** times!"
if self.type is MessageType.premium_guild_tier_1:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**"
if self.type is MessageType.premium_guild_tier_2:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**"
if self.type is MessageType.premium_guild_tier_3:
if not self.content:
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**"
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**"
if self.type is MessageType.channel_follow_add:
return f"{self.author.name} has added {self.content} to this channel"
if self.type is MessageType.guild_stream:
# the author will be a Member
return f"{self.author.name} is live! Now streaming {self.author.activity.name}" # type: ignore
if self.type is MessageType.guild_discovery_disqualified:
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details."
if self.type is MessageType.guild_discovery_requalified:
return "This server is eligible for Server Discovery again and has been automatically relisted!"
if self.type is MessageType.guild_discovery_grace_period_initial_warning:
return "This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery."
if self.type is MessageType.guild_discovery_grace_period_final_warning:
return "This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery."
if self.type is MessageType.thread_created:
return f"{self.author.name} started a thread: **{self.content}**. See all **threads**."
if self.type is MessageType.reply:
return self.content
if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None:
return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore
if self.type is MessageType.guild_invite_reminder:
return "Wondering who to invite?\nStart by inviting anyone who can help you build the server!"
if self.type is MessageType.stage_start:
return f"{self.author.display_name} started {self.content}"
if self.type is MessageType.stage_end:
return f"{self.author.display_name} ended {self.content}"
if self.type is MessageType.stage_speaker:
return f"{self.author.display_name} is now a speaker."
if self.type is MessageType.stage_topic:
return f"{self.author.display_name} changed the Stage topic: {self.content}"
return None
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`~Permissions.manage_messages`
permission.
.. versionchanged:: 1.1
Added the new ``delay`` keyword-only parameter.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message. If the deletion fails then it is silently ignored.
Raises
------
Forbidden
You do not have proper permissions to delete the message.
NotFound
The message was deleted already
HTTPException
Deleting the message failed.
"""
if delay is not None:
async def delete(delay: float) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await self._state.http.delete_message(self.channel.id, self.id)
task = asyncio.create_task(delete(delay))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await self._state.http.delete_message(self.channel.id, self.id)
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
file: Optional[File] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embed: Optional[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
*,
content: Optional[str] = ...,
embeds: List[Embed] = ...,
attachments: List[Attachment] = ...,
suppress: bool = ...,
delete_after: Optional[float] = ...,
allowed_mentions: Optional[AllowedMentions] = ...,
view: Optional[View] = ...,
files: Optional[List[File]] = ...,
) -> Message:
...
async def edit(
self,
content: Optional[str] = MISSING,
embed: Optional[Embed] = MISSING,
embeds: List[Embed] = MISSING,
attachments: List[Attachment] = MISSING,
suppress: bool = MISSING,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
view: Optional[View] = MISSING,
file: Optional[File] = MISSING,
files: Optional[List[File]] = MISSING,
) -> Message:
"""|coro|
Edits the message.
The content must be able to be transformed into a string via ``str(content)``.
.. versionchanged:: 1.3
The ``suppress`` keyword-only parameter was added.
Parameters
----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove the embed.
embeds: List[:class:`Embed`]
The new embeds to replace the original with. Must be a maximum of 10.
To remove all embeds ``[]`` should be passed.
.. versionadded:: 2.0
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep all existing attachments,
pass ``message.attachments``.
suppress: :class:`bool`
Whether to suppress embeds for the message. This removes
all the embeds if set to ``True``. If set to ``False``
this brings the embeds back if they were suppressed.
Using this parameter requires :attr:`~.Permissions.manage_messages`.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~nextcord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~nextcord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~nextcord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~nextcord.Client.allowed_mentions`
are used instead.
.. versionadded:: 1.4
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
file: Optional[:class:`File`]
If provided, a new file to add to the message.
.. versionadded:: 2.0
files: Optional[List[:class:`File`]]
If provided, a list of new files to add to the message.
.. versionadded:: 2.0
Raises
------
HTTPException
Editing the message failed.
Forbidden
Tried to suppress a message without permissions or
edited a message's content or embed that isn't yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
Returns
-------
:class:`Message`
The edited message.
"""
payload: Dict[str, Any] = {}
if content is not MISSING:
if content is not None:
payload["content"] = str(content)
else:
payload["content"] = None
if embed is not MISSING and embeds is not MISSING:
raise InvalidArgument("Cannot pass both embed and embeds parameter to edit()")
if file is not MISSING and files is not MISSING:
raise InvalidArgument("Cannot pass both file and files parameter to edit()")
if embed is not MISSING:
if embed is None:
payload["embeds"] = []
else:
payload["embeds"] = [embed.to_dict()]
elif embeds is not MISSING:
payload["embeds"] = [e.to_dict() for e in embeds]
if suppress is not MISSING:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = suppress
payload["flags"] = flags.value
if allowed_mentions is MISSING:
if self._state.allowed_mentions is not None and self.author.id == self._state.self_id:
payload["allowed_mentions"] = self._state.allowed_mentions.to_dict()
elif allowed_mentions is not None:
if self._state.allowed_mentions is not None:
payload["allowed_mentions"] = self._state.allowed_mentions.merge(
allowed_mentions
).to_dict()
else:
payload["allowed_mentions"] = allowed_mentions.to_dict()
if attachments is not MISSING:
payload["attachments"] = [a.to_dict() for a in attachments]
if view is not MISSING:
self._state.prevent_view_updates_for(self.id)
if view:
payload["components"] = view.to_components()
else:
payload["components"] = []
if file is not MISSING:
payload["files"] = [file]
elif files is not MISSING:
payload["files"] = files
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
message = Message(state=self._state, channel=self.channel, data=data)
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, self.id)
if delete_after is not None:
await self.delete(delay=delete_after)
return message
async def publish(self) -> None:
"""|coro|
Publishes this message to your announcement channel.
You must have the :attr:`~Permissions.send_messages` permission to do this.
If the message is not your own then the :attr:`~Permissions.manage_messages`
permission is also needed.
Raises
------
Forbidden
You do not have the proper permissions to publish this message.
HTTPException
Publishing the message failed.
"""
await self._state.http.publish_message(self.channel.id, self.id)
async def pin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Pins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for pinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to pin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
"""
await self._state.http.pin_message(self.channel.id, self.id, reason=reason)
self.pinned = True
async def unpin(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Parameters
----------
reason: Optional[:class:`str`]
The reason for unpinning the message. Shows up on the audit log.
.. versionadded:: 1.4
Raises
------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or channel was not found or deleted.
HTTPException
Unpinning the message failed.
"""
await self._state.http.unpin_message(self.channel.id, self.id, reason=reason)
self.pinned = False
async def add_reaction(self, emoji: EmojiInputType) -> None:
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_reactions` permission is required.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to react with.
Raises
------
HTTPException
Adding the reaction failed.
Forbidden
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
async def remove_reaction(
self, emoji: Union[EmojiInputType, Reaction], member: Snowflake
) -> None:
"""|coro|
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
If the reaction is not your own (i.e. ``member`` parameter is not you) then
the :attr:`~Permissions.manage_messages` permission is needed.
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to remove.
member: :class:`abc.Snowflake`
The member for which to remove the reaction.
Raises
------
HTTPException
Removing the reaction failed.
Forbidden
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
if member.id == self._state.self_id:
await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji)
else:
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
async def clear_reaction(self, emoji: Union[EmojiInputType, Reaction]) -> None:
"""|coro|
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You need the :attr:`~Permissions.manage_messages` permission to use this.
.. versionadded:: 1.3
Parameters
----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
The emoji to clear.
Raises
------
HTTPException
Clearing the reaction failed.
Forbidden
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
The emoji parameter is invalid.
"""
emoji = convert_emoji_reaction(emoji)
await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji)
async def clear_reactions(self) -> None:
"""|coro|
Removes all the reactions from the message.
You need the :attr:`~Permissions.manage_messages` permission to use this.
Raises
------
HTTPException
Removing the reactions failed.
Forbidden
You do not have the proper permissions to remove all the reactions.
"""
await self._state.http.clear_reactions(self.channel.id, self.id)
async def create_thread(
self, *, name: str, auto_archive_duration: ThreadArchiveDuration = MISSING
) -> Thread:
"""|coro|
Creates a public thread from this message.
You must have :attr:`~nextcord.Permissions.create_public_threads` in order to
create a public thread from a message.
The channel this message belongs in must be a :class:`TextChannel`.
.. versionadded:: 2.0
Parameters
----------
name: :class:`str`
The name of the thread.
auto_archive_duration: :class:`int`
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
Raises
------
Forbidden
You do not have permissions to create a thread.
HTTPException
Creating the thread failed.
InvalidArgument
This message does not have guild info attached.
Returns
-------
:class:`.Thread`
The created thread.
"""
if self.guild is None:
raise InvalidArgument("This message does not have guild info attached.")
default_auto_archive_duration: ThreadArchiveDuration = getattr(
self.channel, "default_auto_archive_duration", 1440
)
data = await self._state.http.start_thread_with_message(
self.channel.id,
self.id,
name=name,
auto_archive_duration=auto_archive_duration or default_auto_archive_duration,
)
return Thread(guild=self.guild, state=self._state, data=data)
async def reply(self, content: Optional[str] = None, **kwargs) -> Message:
"""|coro|
A shortcut method to :meth:`.abc.Messageable.send` to reply to the
:class:`.Message`.
.. versionadded:: 1.6
Raises
------
~nextcord.HTTPException
Sending the message failed.
~nextcord.Forbidden
You do not have the proper permissions to send the message.
~nextcord.InvalidArgument
The ``files`` list is not of the appropriate size or
you specified both ``file`` and ``files``.
Returns
-------
:class:`.Message`
The message that was sent.
"""
return await self.channel.send(content, reference=self, **kwargs)
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a :class:`~nextcord.MessageReference` from the current message.
.. versionadded:: 1.6
Parameters
----------
fail_if_not_exists: :class:`bool`
Whether replying using the message reference should raise :class:`HTTPException`
if the message no longer exists or Discord could not fetch the message.
.. versionadded:: 1.7
Returns
-------
:class:`~nextcord.MessageReference`
The reference to this message.
"""
return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists)
def to_message_reference_dict(self) -> MessageReferencePayload:
data: MessageReferencePayload = {
"message_id": self.id,
"channel_id": self.channel.id,
}
if self.guild is not None:
data["guild_id"] = self.guild.id
return data
The provided code snippet includes necessary dependencies for implementing the `when_mentioned_or` function. Write a Python function `def when_mentioned_or(*prefixes: str) -> Callable[[Union[Bot, AutoShardedBot], Message], List[str]]` to solve the following problem:
A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example ------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also -------- :func:`.when_mentioned`
Here is the function:
def when_mentioned_or(*prefixes: str) -> Callable[[Union[Bot, AutoShardedBot], Message], List[str]]:
"""A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the :attr:`.Bot.command_prefix` attribute.
Example
-------
.. code-block:: python3
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
.. note::
This callable returns another callable, so if this is done inside a custom
callable, you must call the returned callable, for example:
.. code-block:: python3
async def get_prefix(bot, message):
extras = await prefixes_for(message.guild) # returns a list
return commands.when_mentioned_or(*extras)(bot, message)
See Also
--------
:func:`.when_mentioned`
"""
def inner(bot, msg):
r = list(prefixes)
return when_mentioned(bot, msg) + r
return inner | A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. Example ------- .. code-block:: python3 bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) .. note:: This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example: .. code-block:: python3 async def get_prefix(bot, message): extras = await prefixes_for(message.guild) # returns a list return commands.when_mentioned_or(*extras)(bot, message) See Also -------- :func:`.when_mentioned` |
160,913 | from __future__ import annotations
import asyncio
import collections
import collections.abc
import contextlib
import copy
import importlib.util
import inspect
import os
import sys
import traceback
import types
import warnings
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Type,
TypeVar,
Union,
)
import nextcord
from . import errors
from .cog import Cog
from .context import Context
from .core import GroupMixin
from .help import DefaultHelpCommand, HelpCommand
from .view import StringView
def _is_submodule(parent: str, child: str) -> bool:
return parent == child or child.startswith(parent + ".") | null |
160,914 | from __future__ import annotations
import copy
import functools
import itertools
import re
from typing import TYPE_CHECKING, ClassVar, Dict
import nextcord.utils
from .core import Command, Group
from .errors import CommandError
def _not_overriden(f):
f.__help_command_not_overriden__ = True
return f | null |
160,915 | from __future__ import annotations
import inspect
import re
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
List,
Literal,
Optional,
Protocol,
Tuple,
Type,
TypeVar,
Union,
runtime_checkable,
)
import nextcord
from .errors import *
def _get_from_guilds(bot, getter, argument):
result = None
for guild in bot.guilds:
result = getattr(guild, getter)(argument)
if result:
return result
return result | null |
160,916 | from __future__ import annotations
import inspect
import re
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
Iterable,
List,
Literal,
Optional,
Protocol,
Tuple,
Type,
TypeVar,
Union,
runtime_checkable,
)
import nextcord
from .errors import *
def get_converter(param: inspect.Parameter) -> Any:
converter = param.annotation
if converter is param.empty:
if param.default is not param.empty:
converter = str if param.default is None else type(param.default)
else:
converter = str
return converter | null |
160,917 | from typing import Callable, Union
from nextcord import CallbackWrapper, SlashApplicationCommand, SlashApplicationSubcommand
def describe(
**kwargs: str,
) -> Callable[
[Callable], Union[SlashApplicationCommand, SlashApplicationSubcommand, CallbackWrapper]
]:
class DescribeWrapper(CallbackWrapper):
def modify(self, app_cmd: SlashApplicationCommand):
option_names = {option.functional_name: option for option in app_cmd.options.values()}
for given_name in kwargs:
if option := option_names.get(given_name):
option.description = kwargs[given_name]
else:
raise ValueError(
f'{app_cmd.error_name} Could not find option "{given_name}" to describe.'
)
def wrapper(func):
return DescribeWrapper(func)
return wrapper | null |
160,918 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationCheckAnyFailure(ApplicationCheckFailure):
"""Exception raised when all predicates in :func:`check_any` fail.
This inherits from :exc:`~.ApplicationCheckFailure`.
Attributes
----------
errors: List[:class:`~.ApplicationCheckFailure`]
A list of errors that were caught during execution.
checks: List[Callable[[:class:`~.Interaction`], :class:`bool`]]
A list of check predicates that failed.
"""
def __init__(
self,
checks: List[Callable[[Interaction], bool]],
errors: List[ApplicationCheckFailure],
) -> None:
self.checks: List[Callable[[Interaction], bool]] = checks
self.errors: List[ApplicationCheckFailure] = errors
super().__init__("You do not have permission to run this command.")
The provided code snippet includes necessary dependencies for implementing the `check_any` function. Write a Python function `def check_any(*checks: "ApplicationCheck") -> AC` to solve the following problem:
r"""A :func:`check` that will pass if any of the given checks pass, i.e. using logical OR. If all checks fail then :exc:`.ApplicationCheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.ApplicationCheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. Parameters ---------- \*checks: Callable[[:class:`~.Interaction`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------ TypeError A check passed has not been decorated with the :func:`check` decorator. Examples -------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(interaction: Interaction): return ( interaction.guild is not None and interaction.guild.owner_id == interaction.user.id ) return application_checks.check(predicate) @bot.slash_command() @application_checks.check_any(applications_checks.is_owner(), is_guild_owner()) async def only_for_owners(interaction: Interaction): await interaction.response.send_message('Hello mister owner!')
Here is the function:
def check_any(*checks: "ApplicationCheck") -> AC:
r"""A :func:`check` that will pass if any of the given checks pass,
i.e. using logical OR.
If all checks fail then :exc:`.ApplicationCheckAnyFailure` is raised to signal
the failure. It inherits from :exc:`.ApplicationCheckFailure`.
.. note::
The ``predicate`` attribute for this function **is** a coroutine.
Parameters
----------
\*checks: Callable[[:class:`~.Interaction`], :class:`bool`]
An argument list of checks that have been decorated with
the :func:`check` decorator.
Raises
------
TypeError
A check passed has not been decorated with the :func:`check`
decorator.
Examples
--------
Creating a basic check to see if it's the bot owner or
the server owner:
.. code-block:: python3
def is_guild_owner():
def predicate(interaction: Interaction):
return (
interaction.guild is not None
and interaction.guild.owner_id == interaction.user.id
)
return application_checks.check(predicate)
@bot.slash_command()
@application_checks.check_any(applications_checks.is_owner(), is_guild_owner())
async def only_for_owners(interaction: Interaction):
await interaction.response.send_message('Hello mister owner!')
"""
unwrapped = []
for wrapped in checks:
try:
# we only want to get the predicate, the arg type is not used
wrapper = wrapped(None) # type: ignore
pred = wrapper.predicate # type: ignore
except AttributeError:
raise TypeError(
f"{wrapped!r} must be wrapped by application_checks.check decorator"
) from None
else:
unwrapped.append(pred)
async def predicate(interaction: Interaction) -> bool:
errors = []
for func in unwrapped:
try:
value = await func(interaction)
except ApplicationCheckFailure as e:
errors.append(e)
else:
if value:
return True
# if we're here, all checks failed
raise ApplicationCheckAnyFailure(unwrapped, errors)
return check(predicate) | r"""A :func:`check` that will pass if any of the given checks pass, i.e. using logical OR. If all checks fail then :exc:`.ApplicationCheckAnyFailure` is raised to signal the failure. It inherits from :exc:`.ApplicationCheckFailure`. .. note:: The ``predicate`` attribute for this function **is** a coroutine. Parameters ---------- \*checks: Callable[[:class:`~.Interaction`], :class:`bool`] An argument list of checks that have been decorated with the :func:`check` decorator. Raises ------ TypeError A check passed has not been decorated with the :func:`check` decorator. Examples -------- Creating a basic check to see if it's the bot owner or the server owner: .. code-block:: python3 def is_guild_owner(): def predicate(interaction: Interaction): return ( interaction.guild is not None and interaction.guild.owner_id == interaction.user.id ) return application_checks.check(predicate) @bot.slash_command() @application_checks.check_any(applications_checks.is_owner(), is_guild_owner()) async def only_for_owners(interaction: Interaction): await interaction.response.send_message('Hello mister owner!') |
160,919 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationMissingRole(ApplicationCheckFailure):
"""Exception raised when the command invoker lacks a role to run a command.
This inherits from :exc:`~.ApplicationCheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_role: Union[:class:`str`, :class:`int`]
The required role that is missing.
This is the parameter passed to :func:`~.application_checks.has_role`.
"""
def __init__(self, missing_role: Union[str, int]) -> None:
self.missing_role: Union[str, int] = missing_role
message = f"Role {missing_role!r} is required to run this command."
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `has_role` function. Write a Python function `def has_role(item: Union[int, str]) -> AC` to solve the following problem:
A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_role('Cool Role') async def cool(interaction: Interaction): await interaction.response.send_message('You are cool indeed')
Here is the function:
def has_role(item: Union[int, str]) -> AC:
"""A :func:`.check` that is added that checks if the member invoking the
command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including
caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will
return ``False``.
This check raises one of two special exceptions, :exc:`.MissingRole` if the user
is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.ApplicationCheckFailure`.
Parameters
----------
item: Union[:class:`int`, :class:`str`]
The name or ID of the role to check.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.has_role('Cool Role')
async def cool(interaction: Interaction):
await interaction.response.send_message('You are cool indeed')
"""
def predicate(interaction: Interaction) -> bool:
if interaction.guild is None:
raise ApplicationNoPrivateMessage
# interaction.guild is None doesn't narrow interaction.user to Member
if isinstance(item, int):
role = nextcord.utils.get(interaction.user.roles, id=item) # type: ignore
else:
role = nextcord.utils.get(interaction.user.roles, name=item) # type: ignore
if role is None:
raise ApplicationMissingRole(item)
return True
return check(predicate) | A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the role. If the message is invoked in a private message context then the check will return ``False``. This check raises one of two special exceptions, :exc:`.MissingRole` if the user is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_role('Cool Role') async def cool(interaction: Interaction): await interaction.response.send_message('You are cool indeed') |
160,920 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationMissingAnyRole(ApplicationCheckFailure):
"""Exception raised when the command invoker lacks any of
the roles specified to run a command.
This inherits from :exc:`~.ApplicationCheckFailure`
Attributes
----------
missing_roles: List[Union[:class:`str`, :class:`int`]]
The roles that the invoker is missing.
These are the parameters passed to :func:`has_any_role`.
"""
def __init__(self, missing_roles: List[Union[str, int]]) -> None:
self.missing_roles: List[Union[str, int]] = missing_roles
missing = [f"'{role}'" for role in missing_roles]
if len(missing) > 2:
fmt = "{}, or {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " or ".join(missing)
message = f"You are missing at least one of the required roles: {fmt}"
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `has_any_role` function. Write a Python function `def has_any_role(*items: Union[int, str]) -> AC` to solve the following problem:
r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return ``True``. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_any_role('Moderators', 492212595072434186) async def cool(interaction: Interaction): await interaction.response.send_message('You are cool indeed')
Here is the function:
def has_any_role(*items: Union[int, str]) -> AC:
r"""A :func:`.check` that is added that checks if the member invoking the
command has **any** of the roles specified. This means that if they have
one out of the three roles specified, then this check will return ``True``.
Similar to :func:`.has_role`\, the names or IDs passed in must be exact.
This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.ApplicationCheckFailure`.
Parameters
----------
items: List[Union[:class:`str`, :class:`int`]]
An argument list of names or IDs to check that the member has roles wise.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.has_any_role('Moderators', 492212595072434186)
async def cool(interaction: Interaction):
await interaction.response.send_message('You are cool indeed')
"""
def predicate(interaction: Interaction) -> bool:
if interaction.guild is None:
raise ApplicationNoPrivateMessage
# interaction.guild is None doesn't narrow interaction.user to Member
getter = functools.partial(nextcord.utils.get, interaction.user.roles) # type: ignore
if any(
getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None
for item in items
):
return True
raise ApplicationMissingAnyRole(list(items))
return check(predicate) | r"""A :func:`.check` that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return ``True``. Similar to :func:`.has_role`\, the names or IDs passed in must be exact. This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- items: List[Union[:class:`str`, :class:`int`]] An argument list of names or IDs to check that the member has roles wise. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_any_role('Moderators', 492212595072434186) async def cool(interaction: Interaction): await interaction.response.send_message('You are cool indeed') |
160,921 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationBotMissingRole(ApplicationCheckFailure):
"""Exception raised when the bot's member lacks a role to run a command.
This inherits from :exc:`~.ApplicationCheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_role: Union[:class:`str`, :class:`int`]
The required role that is missing.
This is the parameter passed to :func:`has_role`.
"""
def __init__(self, missing_role: Union[str, int]) -> None:
self.missing_role: Union[str, int] = missing_role
message = f"Bot requires the role {missing_role!r} to run this command"
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `bot_has_role` function. Write a Python function `def bot_has_role(item: Union[int, str]) -> AC` to solve the following problem:
Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.ApplicationBotMissingRole` if the bot is missing the role, or :exc:`.ApplicationNoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.bot_has_role(492212595072434186) async def hasrole(interaction: Interaction): await interaction.response.send_message('I have the required role!')
Here is the function:
def bot_has_role(item: Union[int, str]) -> AC:
"""Similar to :func:`.has_role` except checks if the bot itself has the
role.
This check raises one of two special exceptions,
:exc:`.ApplicationBotMissingRole` if the bot is missing the role,
or :exc:`.ApplicationNoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.ApplicationCheckFailure`.
Parameters
----------
item: Union[:class:`int`, :class:`str`]
The name or ID of the role to check.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.bot_has_role(492212595072434186)
async def hasrole(interaction: Interaction):
await interaction.response.send_message('I have the required role!')
"""
def predicate(interaction: Interaction) -> bool:
if interaction.guild is None:
raise ApplicationNoPrivateMessage
me = interaction.guild.me
if isinstance(item, int):
role = nextcord.utils.get(me.roles, id=item)
else:
role = nextcord.utils.get(me.roles, name=item)
if role is None:
raise ApplicationBotMissingRole(item)
return True
return check(predicate) | Similar to :func:`.has_role` except checks if the bot itself has the role. This check raises one of two special exceptions, :exc:`.ApplicationBotMissingRole` if the bot is missing the role, or :exc:`.ApplicationNoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- item: Union[:class:`int`, :class:`str`] The name or ID of the role to check. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.bot_has_role(492212595072434186) async def hasrole(interaction: Interaction): await interaction.response.send_message('I have the required role!') |
160,922 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationBotMissingAnyRole(ApplicationCheckFailure):
"""Exception raised when the bot's member lacks any of
the roles specified to run a command.
This inherits from :exc:`~.ApplicationCheckFailure`
.. versionadded:: 1.1
Attributes
----------
missing_roles: List[Union[:class:`str`, :class:`int`]]
The roles that the bot's member is missing.
These are the parameters passed to :func:`has_any_role`.
"""
def __init__(self, missing_roles: List[Union[str, int]]) -> None:
self.missing_roles: List[Union[str, int]] = missing_roles
missing = [f"'{role}'" for role in missing_roles]
if len(missing) > 2:
fmt = "{}, or {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " or ".join(missing)
message = f"Bot is missing at least one of the required roles: {fmt}"
super().__init__(message)
The provided code snippet includes necessary dependencies for implementing the `bot_has_any_role` function. Write a Python function `def bot_has_any_role(*items: Union[str, int]) -> AC` to solve the following problem:
Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.ApplicationBotMissingAnyRole` if the bot is missing all roles, or :exc:`.ApplicationNoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- *items: Union[:class:`str`, :class:`int`] An argument list of names or IDs to check that the bot has roles wise. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.bot_has_any_role('Moderators', 492212595072434186) async def cool(interaction: Interaction): await interaction.response.send_message('I have a required role!')
Here is the function:
def bot_has_any_role(*items: Union[str, int]) -> AC:
"""Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions,
:exc:`.ApplicationBotMissingAnyRole` if the bot is missing all roles,
or :exc:`.ApplicationNoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.ApplicationCheckFailure`.
Parameters
----------
*items: Union[:class:`str`, :class:`int`]
An argument list of names or IDs to check that the bot has roles wise.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.bot_has_any_role('Moderators', 492212595072434186)
async def cool(interaction: Interaction):
await interaction.response.send_message('I have a required role!')
"""
def predicate(interaction: Interaction) -> bool:
if interaction.guild is None:
raise ApplicationNoPrivateMessage
getter = functools.partial(nextcord.utils.get, interaction.guild.me.roles)
if any(
getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None
for item in items
):
return True
raise ApplicationBotMissingAnyRole(list(items))
return check(predicate) | Similar to :func:`.has_any_role` except checks if the bot itself has any of the roles listed. This check raises one of two special exceptions, :exc:`.ApplicationBotMissingAnyRole` if the bot is missing all roles, or :exc:`.ApplicationNoPrivateMessage` if it is used in a private message. Both inherit from :exc:`.ApplicationCheckFailure`. Parameters ---------- *items: Union[:class:`str`, :class:`int`] An argument list of names or IDs to check that the bot has roles wise. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.bot_has_any_role('Moderators', 492212595072434186) async def cool(interaction: Interaction): await interaction.response.send_message('I have a required role!') |
160,923 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def _permission_check_wrapper(predicate: ApplicationCheck, name: str, perms: Dict[str, bool]) -> AC:
def wrapper(func) -> CheckWrapper:
callback = func.callback if isinstance(func, CallbackWrapper) else func
setattr(callback, name, perms)
return check(predicate)(func) # type: ignore
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationMissingPermissions(ApplicationCheckFailure):
"""Exception raised when the command invoker lacks permissions to run a
command.
This inherits from :exc:`~.ApplicationCheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"You are missing {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `has_permissions` function. Write a Python function `def has_permissions(**perms: bool) -> AC` to solve the following problem:
A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.nextcord.Permissions`. This check raises a special exception, :exc:`.ApplicationMissingPermissions` that is inherited from :exc:`.ApplicationCheckFailure`. If this check is called in a DM context, it will raise an exception, :exc:`.ApplicationNoPrivateMessage`. Parameters ---------- perms: :class:`bool` An argument list of permissions to check for. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_permissions(manage_messages=True) async def testperms(interaction: Interaction): await interaction.response.send_message('You can manage messages.')
Here is the function:
def has_permissions(**perms: bool) -> AC:
"""A :func:`.check` that is added that checks if the member has all of
the permissions necessary.
Note that this check operates on the current channel permissions, not the
guild wide permissions.
The permissions passed in must be exactly like the properties shown under
:class:`.nextcord.Permissions`.
This check raises a special exception, :exc:`.ApplicationMissingPermissions`
that is inherited from :exc:`.ApplicationCheckFailure`.
If this check is called in a DM context, it will raise an
exception, :exc:`.ApplicationNoPrivateMessage`.
Parameters
----------
perms: :class:`bool`
An argument list of permissions to check for.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.has_permissions(manage_messages=True)
async def testperms(interaction: Interaction):
await interaction.response.send_message('You can manage messages.')
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(interaction: Interaction) -> bool:
ch = interaction.channel
try:
permissions = ch.permissions_for(interaction.user) # type: ignore
except AttributeError:
raise ApplicationNoPrivateMessage from None
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise ApplicationMissingPermissions(missing)
return _permission_check_wrapper(predicate, "__slash_required_permissions", perms) | A :func:`.check` that is added that checks if the member has all of the permissions necessary. Note that this check operates on the current channel permissions, not the guild wide permissions. The permissions passed in must be exactly like the properties shown under :class:`.nextcord.Permissions`. This check raises a special exception, :exc:`.ApplicationMissingPermissions` that is inherited from :exc:`.ApplicationCheckFailure`. If this check is called in a DM context, it will raise an exception, :exc:`.ApplicationNoPrivateMessage`. Parameters ---------- perms: :class:`bool` An argument list of permissions to check for. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_permissions(manage_messages=True) async def testperms(interaction: Interaction): await interaction.response.send_message('You can manage messages.') |
160,924 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def _permission_check_wrapper(predicate: ApplicationCheck, name: str, perms: Dict[str, bool]) -> AC:
def wrapper(func) -> CheckWrapper:
callback = func.callback if isinstance(func, CallbackWrapper) else func
setattr(callback, name, perms)
return check(predicate)(func) # type: ignore
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationBotMissingPermissions(ApplicationCheckFailure):
"""Exception raised when the bot's member lacks permissions to run a
command.
This inherits from :exc:`~.ApplicationCheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"Bot requires {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `bot_has_permissions` function. Write a Python function `def bot_has_permissions(**perms: bool) -> AC` to solve the following problem:
Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.ApplicationBotMissingPermissions` that is inherited from :exc:`.ApplicationCheckFailure`. If this check is called in a DM context, it will raise an exception, :exc:`.ApplicationNoPrivateMessage`.
Here is the function:
def bot_has_permissions(**perms: bool) -> AC:
"""Similar to :func:`.has_permissions` except checks if the bot itself has
the permissions listed.
This check raises a special exception, :exc:`.ApplicationBotMissingPermissions`
that is inherited from :exc:`.ApplicationCheckFailure`.
If this check is called in a DM context, it will raise an
exception, :exc:`.ApplicationNoPrivateMessage`.
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(interaction: Interaction) -> bool:
guild = interaction.guild
me = guild.me if guild is not None else interaction.client.user
ch = interaction.channel
try:
permissions = ch.permissions_for(me) # type: ignore
except AttributeError:
raise ApplicationNoPrivateMessage from None
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise ApplicationBotMissingPermissions(missing)
return _permission_check_wrapper(predicate, "__slash_required_bot_permissions", perms) | Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.ApplicationBotMissingPermissions` that is inherited from :exc:`.ApplicationCheckFailure`. If this check is called in a DM context, it will raise an exception, :exc:`.ApplicationNoPrivateMessage`. |
160,925 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def _permission_check_wrapper(predicate: ApplicationCheck, name: str, perms: Dict[str, bool]) -> AC:
def wrapper(func) -> CheckWrapper:
callback = func.callback if isinstance(func, CallbackWrapper) else func
setattr(callback, name, perms)
return check(predicate)(func) # type: ignore
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationMissingPermissions(ApplicationCheckFailure):
"""Exception raised when the command invoker lacks permissions to run a
command.
This inherits from :exc:`~.ApplicationCheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"You are missing {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `has_guild_permissions` function. Write a Python function `def has_guild_permissions(**perms: bool) -> AC` to solve the following problem:
Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.ApplicationNoPrivateMessage`. Parameters ---------- perms: :class:`bool` An argument list of guild permissions to check for. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_guild_permissions(manage_messages=True) async def permcmd(interaction: Interaction): await interaction.response.send_message('You can manage messages!')
Here is the function:
def has_guild_permissions(**perms: bool) -> AC:
"""Similar to :func:`.has_permissions`, but operates on guild wide
permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an
exception, :exc:`.ApplicationNoPrivateMessage`.
Parameters
----------
perms: :class:`bool`
An argument list of guild permissions to check for.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.has_guild_permissions(manage_messages=True)
async def permcmd(interaction: Interaction):
await interaction.response.send_message('You can manage messages!')
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(interaction: Interaction) -> bool:
if not interaction.guild:
raise ApplicationNoPrivateMessage
permissions = interaction.user.guild_permissions # type: ignore
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise ApplicationMissingPermissions(missing)
return _permission_check_wrapper(predicate, "__slash_required_guild_permissions", perms) | Similar to :func:`.has_permissions`, but operates on guild wide permissions instead of the current channel permissions. If this check is called in a DM context, it will raise an exception, :exc:`.ApplicationNoPrivateMessage`. Parameters ---------- perms: :class:`bool` An argument list of guild permissions to check for. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.has_guild_permissions(manage_messages=True) async def permcmd(interaction: Interaction): await interaction.response.send_message('You can manage messages!') |
160,926 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def _permission_check_wrapper(predicate: ApplicationCheck, name: str, perms: Dict[str, bool]) -> AC:
def wrapper(func) -> CheckWrapper:
callback = func.callback if isinstance(func, CallbackWrapper) else func
setattr(callback, name, perms)
return check(predicate)(func) # type: ignore
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
class ApplicationBotMissingPermissions(ApplicationCheckFailure):
"""Exception raised when the bot's member lacks permissions to run a
command.
This inherits from :exc:`~.ApplicationCheckFailure`
Attributes
----------
missing_permissions: List[:class:`str`]
The required permissions that are missing.
"""
def __init__(self, missing_permissions: List[str], *args: Any) -> None:
self.missing_permissions: List[str] = missing_permissions
missing = [
perm.replace("_", " ").replace("guild", "server").title()
for perm in missing_permissions
]
if len(missing) > 2:
fmt = "{}, and {}".format(", ".join(missing[:-1]), missing[-1])
else:
fmt = " and ".join(missing)
message = f"Bot requires {fmt} permission(s) to run this command."
super().__init__(message, *args)
The provided code snippet includes necessary dependencies for implementing the `bot_has_guild_permissions` function. Write a Python function `def bot_has_guild_permissions(**perms: bool) -> AC` to solve the following problem:
Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions.
Here is the function:
def bot_has_guild_permissions(**perms: bool) -> AC:
"""Similar to :func:`.has_guild_permissions`, but checks the bot
members guild permissions.
"""
invalid = set(perms) - set(nextcord.Permissions.VALID_FLAGS)
if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
def predicate(interaction: Interaction) -> bool:
if not interaction.guild:
raise ApplicationNoPrivateMessage
permissions = interaction.guild.me.guild_permissions
missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]
if not missing:
return True
raise ApplicationBotMissingPermissions(missing)
return _permission_check_wrapper(predicate, "__slash_required_bot_guild_permissions", perms) | Similar to :func:`.has_guild_permissions`, but checks the bot members guild permissions. |
160,927 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationPrivateMessageOnly(ApplicationCheckFailure):
"""Exception raised when an operation does not work outside of private
message contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command can only be used in private messages.")
The provided code snippet includes necessary dependencies for implementing the `dm_only` function. Write a Python function `def dm_only() -> AC` to solve the following problem:
A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationPrivateMessageOnly` that is inherited from :exc:`.ApplicationCheckFailure`. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.dm_only() async def dmcmd(interaction: Interaction): await interaction.response.send_message('This is in DMS!')
Here is the function:
def dm_only() -> AC:
"""A :func:`.check` that indicates this command must only be used in a
DM context. Only private messages are allowed when
using the command.
This check raises a special exception, :exc:`.ApplicationPrivateMessageOnly`
that is inherited from :exc:`.ApplicationCheckFailure`.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.dm_only()
async def dmcmd(interaction: Interaction):
await interaction.response.send_message('This is in DMS!')
"""
def predicate(interaction: Interaction) -> bool:
if interaction.guild is not None:
raise ApplicationPrivateMessageOnly
return True
return check(predicate) | A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationPrivateMessageOnly` that is inherited from :exc:`.ApplicationCheckFailure`. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.dm_only() async def dmcmd(interaction: Interaction): await interaction.response.send_message('This is in DMS!') |
160,928 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNoPrivateMessage(ApplicationCheckFailure):
"""Exception raised when an operation does not work in private message
contexts.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self, message: Optional[str] = None) -> None:
super().__init__(message or "This command cannot be used in private messages.")
The provided code snippet includes necessary dependencies for implementing the `guild_only` function. Write a Python function `def guild_only() -> AC` to solve the following problem:
A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationNoPrivateMessage` that is inherited from :exc:`.ApplicationCheckFailure`. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.guild_only() async def dmcmd(interaction: Interaction): await interaction.response.send_message('This is in a GUILD!')
Here is the function:
def guild_only() -> AC:
"""A :func:`.check` that indicates this command must only be used in a
guild context only. Basically, no private messages are allowed when
using the command.
This check raises a special exception, :exc:`.ApplicationNoPrivateMessage`
that is inherited from :exc:`.ApplicationCheckFailure`.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.guild_only()
async def dmcmd(interaction: Interaction):
await interaction.response.send_message('This is in a GUILD!')
"""
def predicate(interaction: Interaction) -> bool:
if interaction.guild is None:
raise ApplicationNoPrivateMessage
return True
return check(predicate) | A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationNoPrivateMessage` that is inherited from :exc:`.ApplicationCheckFailure`. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.guild_only() async def dmcmd(interaction: Interaction): await interaction.response.send_message('This is in a GUILD!') |
160,929 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNotOwner(ApplicationCheckFailure):
"""Exception raised when the message author is not the owner of the bot.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
class ApplicationCheckForBotOnly(ApplicationCheckFailure):
"""Exception raised when the application check may only be used for :class:`~ext.commands.Bot`.
This inherits from :exc:`~.ApplicationCheckFailure`
"""
def __init__(self) -> None:
super().__init__("This application check can only be used for ext.commands.Bot.")
The provided code snippet includes necessary dependencies for implementing the `is_owner` function. Write a Python function `def is_owner() -> AC` to solve the following problem:
A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.ext.commands.Bot.is_owner`. This check raises a special exception, :exc:`.ApplicationNotOwner` that is derived from :exc:`.ApplicationCheckFailure`. This check may only be used with :class:`~ext.commands.Bot`. Otherwise, it will raise :exc:`.ApplicationCheckForBotOnly`. Example ------- .. code-block:: python3 bot = commands.Bot(owner_id=297045071457681409) @bot.slash_command() @application_checks.is_owner() async def ownercmd(interaction: Interaction): await interaction.response.send_message('Only you!')
Here is the function:
def is_owner() -> AC:
"""A :func:`.check` that checks if the person invoking this command is the
owner of the bot.
This is powered by :meth:`.ext.commands.Bot.is_owner`.
This check raises a special exception, :exc:`.ApplicationNotOwner` that is derived
from :exc:`.ApplicationCheckFailure`.
This check may only be used with :class:`~ext.commands.Bot`. Otherwise, it will
raise :exc:`.ApplicationCheckForBotOnly`.
Example
-------
.. code-block:: python3
bot = commands.Bot(owner_id=297045071457681409)
@bot.slash_command()
@application_checks.is_owner()
async def ownercmd(interaction: Interaction):
await interaction.response.send_message('Only you!')
"""
async def predicate(interaction: Interaction) -> bool:
if not hasattr(interaction.client, "is_owner"):
raise ApplicationCheckForBotOnly
if not await interaction.client.is_owner(interaction.user):
raise ApplicationNotOwner("You do not own this bot.")
return True
return check(predicate) | A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.ext.commands.Bot.is_owner`. This check raises a special exception, :exc:`.ApplicationNotOwner` that is derived from :exc:`.ApplicationCheckFailure`. This check may only be used with :class:`~ext.commands.Bot`. Otherwise, it will raise :exc:`.ApplicationCheckForBotOnly`. Example ------- .. code-block:: python3 bot = commands.Bot(owner_id=297045071457681409) @bot.slash_command() @application_checks.is_owner() async def ownercmd(interaction: Interaction): await interaction.response.send_message('Only you!') |
160,930 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
def check(predicate: "ApplicationCheck") -> AC:
r"""A decorator that adds a check to the :class:`.BaseApplicationCommand` or its
subclasses. These checks are accessible via :attr:`.BaseApplicationCommand.checks`.
These checks should be predicates that take in a single parameter taking
a :class:`.Interaction`. If the check returns a ``False``\-like value,
an ApplicationCheckFailure is raised during invocation and sent to the
:func:`.on_application_command_error` event.
If an exception should be thrown in the predicate then it should be a
subclass of :exc:`.ApplicationError`. Any exception not subclassed from it
will be propagated while those subclassed will be sent to
:func:`on_application_command_error`.
A special attribute named ``predicate`` is bound to the value
returned by this decorator to retrieve the predicate passed to the
decorator. This allows the following introspection and chaining to be done:
.. code-block:: python3
def owner_or_permissions(**perms):
original = application_checks.has_permissions(**perms).predicate
async def extended_check(interaction: Interaction):
if interaction.guild is None:
return False
return (
interaction.guild.owner_id == interaction.user.id
or await original(interaction)
)
return application_checks.check(extended_check)
.. note::
The function returned by ``predicate`` is **always** a coroutine,
even if the original function was not a coroutine.
Examples
--------
Creating a basic check to see if the command invoker is you.
.. code-block:: python3
def check_if_it_is_me(interaction: Interaction):
return interaction.message.author.id == 85309593344815104
async def only_for_me(interaction: Interaction):
await interaction.response.send_message('I know you!')
Transforming common checks into its own decorator:
.. code-block:: python3
def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')
Parameters
----------
predicate: Callable[[:class:`~.Interaction`], :class:`bool`]
The predicate to check if the command should be invoked.
"""
def wrapper(func):
return CheckWrapper(func, predicate)
wrapper.predicate = predicate
return wrapper
class Interaction(Hashable, Generic[ClientT]):
"""Represents a Discord interaction.
An interaction happens when a user does an action that needs to
be notified. Current examples are slash commands and components.
.. container:: operations
.. describe:: x == y
Checks if two interactions are equal.
.. describe:: x != y
Checks if two interactions are not equal.
.. describe:: hash(x)
Returns the interaction's hash.
.. versionadded:: 2.0
.. versionchanged:: 2.1
:class:`Interaction` is now hashable.
Attributes
----------
id: :class:`int`
The interaction's ID.
type: :class:`InteractionType`
The interaction type.
guild_id: Optional[:class:`int`]
The guild ID the interaction was sent from.
channel_id: Optional[:class:`int`]
The channel ID the interaction was sent from.
locale: Optional[:class:`str`]
The users locale.
guild_locale: Optional[:class:`str`]
The guilds preferred locale, if invoked in a guild.
application_id: :class:`int`
The application ID that the interaction was for.
user: Optional[Union[:class:`User`, :class:`Member`]]
The user or member that sent the interaction.
message: Optional[:class:`Message`]
The message that sent this interaction.
token: :class:`str`
The token to continue the interaction. These are valid
for 15 minutes.
data: :class:`dict`
The raw interaction data.
attached: :class:`InteractionAttached`
The attached data of the interaction. This is used to store any data you may need inside the interaction for convenience. This data will stay on the interaction, even after a :meth:`Interaction.application_command_before_invoke`.
application_command: Optional[:class:`ApplicationCommand`]
The application command that handled the interaction.
"""
__slots__: Tuple[str, ...] = (
"id",
"type",
"guild_id",
"channel_id",
"data",
"application_id",
"message",
"user",
"locale",
"guild_locale",
"token",
"version",
"application_command",
"attached",
"_background_tasks",
"_permissions",
"_app_permissions",
"_state",
"_session",
"_original_message",
"_cs_response",
"_cs_followup",
"_cs_channel",
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState) -> None:
self._state: ConnectionState = state
self._session: ClientSession = state.http._HTTPClient__session # type: ignore
# TODO: this is so janky, accessing a hidden double attribute
self._original_message: Optional[InteractionMessage] = None
self.attached = InteractionAttached()
self.application_command: Optional[
Union[SlashApplicationSubcommand, BaseApplicationCommand]
] = None
self._background_tasks: Set[asyncio.Task] = set()
self._from_data(data)
def _from_data(self, data: InteractionPayload) -> None:
self.id: int = int(data["id"])
self.type: InteractionType = try_enum(InteractionType, data["type"])
self.data: Optional[InteractionData] = data.get("data")
self.token: str = data["token"]
self.version: int = data["version"]
self.channel_id: Optional[int] = utils.get_as_snowflake(data, "channel_id")
self.guild_id: Optional[int] = utils.get_as_snowflake(data, "guild_id")
self.application_id: int = int(data["application_id"])
self.locale: Optional[str] = data.get("locale")
self.guild_locale: Optional[str] = data.get("guild_locale")
self.message: Optional[Message]
try:
message = data["message"]
self.message = self._state._get_message(int(message["id"])) or Message(
state=self._state, channel=self.channel, data=message # type: ignore
)
except KeyError:
self.message = None
self.user: Optional[Union[User, Member]] = None
self._app_permissions: int = int(data.get("app_permissions", 0))
self._permissions: int = 0
# TODO: there's a potential data loss here
if self.guild_id:
guild = self.guild or Object(id=self.guild_id)
try:
member = data["member"]
except KeyError:
pass
else:
cached_member = self.guild and self.guild.get_member(int(member["user"]["id"])) # type: ignore # user key should be present here
self.user = cached_member or Member(state=self._state, guild=guild, data=member) # type: ignore # user key should be present here
self._permissions = int(member.get("permissions", 0))
else:
try:
user = data["user"]
self.user = self._state.get_user(int(user["id"])) or User(
state=self._state, data=user
)
except KeyError:
pass
def client(self) -> ClientT:
""":class:`Client`: The client that handled the interaction."""
return self._state._get_client() # type: ignore
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild the interaction was sent from."""
return self._state and self._state._get_guild(self.guild_id)
def created_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the creation time of the interaction."""
return snowflake_time(self.id)
def expires_at(self) -> datetime:
""":class:`datetime.datetime`: An aware datetime in UTC representing the time when the interaction will expire."""
if self.response.is_done():
return self.created_at + timedelta(minutes=15)
return self.created_at + timedelta(seconds=3)
def is_expired(self) -> bool:
""":class:`bool` A boolean whether the interaction token is invalid or not."""
return utils.utcnow() > self.expires_at
def _set_application_command(
self, app_cmd: Union[SlashApplicationSubcommand, BaseApplicationCommand]
) -> None:
self.application_command = app_cmd
def channel(self) -> Optional[InteractionChannel]:
"""Optional[Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]]: The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:`PartialMessageable` instead.
"""
guild = self.guild
channel = guild and guild._resolve_channel(self.channel_id)
if channel is None:
if self.channel_id is not None:
type = ChannelType.text if self.guild_id is not None else ChannelType.private
return PartialMessageable(state=self._state, id=self.channel_id, type=type)
return None
return channel
def permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the member in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._permissions)
def app_permissions(self) -> Permissions:
""":class:`Permissions`: The resolved permissions of the bot in the channel, including overwrites.
In a non-guild context where this doesn't apply, an empty permissions object is returned.
"""
return Permissions(self._app_permissions)
def response(self) -> InteractionResponse:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using :attr:`followup`
instead.
"""
return InteractionResponse(self)
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": 3,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)
async def original_message(self) -> InteractionMessage:
"""|coro|
Fetches the original interaction response message associated with the interaction.
If the interaction response was :meth:`InteractionResponse.send_message` then this would
return the message that was sent using that response. Otherwise, this would return
the message that triggered the interaction.
Repeated calls to this will return a cached value.
Raises
------
HTTPException
Fetching the original response message failed.
ClientException
The channel for the message could not be resolved.
Returns
-------
InteractionMessage
The original interaction response message.
"""
if self._original_message is not None:
return self._original_message
# TODO: fix later to not raise?
channel = self.channel
if channel is None:
raise ClientException("Channel for message could not be resolved")
adapter = async_context.get()
data = await adapter.get_original_interaction_response(
application_id=self.application_id,
token=self.token,
session=self._session,
)
state = _InteractionMessageState(self, self._state)
message = InteractionMessage(state=state, channel=channel, data=data) # type: ignore
self._original_message = message
return message
async def edit_original_message(
self,
*,
content: Optional[str] = MISSING,
embeds: List[Embed] = MISSING,
embed: Optional[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
attachments: List[Attachment] = MISSING,
view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None,
) -> InteractionMessage:
"""|coro|
Edits the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.edit` in case
you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if
the message sent was ephemeral.
Parameters
----------
content: Optional[:class:`str`]
The content to edit the message with or ``None`` to clear it.
embeds: List[:class:`Embed`]
A list of embeds to edit the message with.
embed: Optional[:class:`Embed`]
The embed to edit the message with. ``None`` suppresses the embeds.
This should not be mixed with the ``embeds`` parameter.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
attachments: List[:class:`Attachment`]
A list of attachments to keep in the message. To keep existing attachments,
you must fetch the message with :meth:`original_message` and pass
``message.attachments`` to this parameter.
allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~nextcord.ui.View`]
The updated view to update this message with. If ``None`` is passed then
the view is removed.
Raises
------
HTTPException
Editing the message failed.
Forbidden
Edited a message that is not yours.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
:class:`InteractionMessage`
The newly edited message.
"""
previous_mentions: Optional[AllowedMentions] = self._state.allowed_mentions
params = handle_message_parameters(
content=content,
file=file,
files=files,
attachments=attachments,
embed=embed,
embeds=embeds,
view=view,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions,
)
adapter = async_context.get()
data = await adapter.edit_original_interaction_response(
self.application_id,
self.token,
session=self._session,
payload=params.payload,
multipart=params.multipart,
files=params.files,
)
# The message channel types should always match
message = InteractionMessage(state=self._state, channel=self.channel, data=data) # type: ignore
if view and not view.is_finished() and view.prevent_update:
self._state.store_view(view, message.id)
return message
async def delete_original_message(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
"""
adapter = async_context.get()
delete_func = adapter.delete_original_interaction_response(
self.application_id,
self.token,
session=self._session,
)
if delay is not None:
async def inner_call(delay: float = delay) -> None:
await asyncio.sleep(delay)
with contextlib.suppress(HTTPException):
await delete_func
task = asyncio.create_task(inner_call())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
else:
await delete_func
async def send(
self,
content: Optional[str] = None,
*,
embed: Embed = MISSING,
embeds: List[Embed] = MISSING,
file: File = MISSING,
files: List[File] = MISSING,
view: View = MISSING,
tts: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: AllowedMentions = MISSING,
flags: Optional[MessageFlags] = None,
ephemeral: Optional[bool] = None,
suppress_embeds: Optional[bool] = None,
) -> Union[PartialInteractionMessage, WebhookMessage]:
"""|coro|
This is a shorthand function for helping in sending messages in
response to an interaction. If the interaction has not been responded to,
:meth:`InteractionResponse.send_message` is used. If the response
:meth:`~InteractionResponse.is_done` then the message is sent
via :attr:`Interaction.followup` using :class:`Webhook.send` instead.
Raises
------
HTTPException
Sending the message failed.
NotFound
The interaction has expired or the interaction has been responded to
but the followup webhook is expired.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
Returns
-------
Union[:class:`PartialInteractionMessage`, :class:`WebhookMessage`]
If the interaction has not been responded to, returns a :class:`PartialInteractionMessage`
supporting only the :meth:`~PartialInteractionMessage.edit` and :meth:`~PartialInteractionMessage.delete`
operations. To fetch the :class:`InteractionMessage` you may use :meth:`~PartialInteractionMessage.fetch`
or :meth:`Interaction.original_message`.
If the interaction has been responded to, returns the :class:`WebhookMessage`.
"""
if not self.response.is_done():
return await self.response.send_message(
content=content,
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
return await self.followup.send(
content=content, # type: ignore
embed=embed,
embeds=embeds,
file=file,
files=files,
view=view,
tts=tts,
ephemeral=ephemeral,
delete_after=delete_after,
allowed_mentions=allowed_mentions,
flags=flags,
suppress_embeds=suppress_embeds,
)
async def edit(self, *args, **kwargs) -> Optional[Message]:
"""|coro|
This is a shorthand function for helping in editing messages in
response to a component or modal submit interaction. If the
interaction has not been responded to, :meth:`InteractionResponse.edit_message`
is used. If the response :meth:`~InteractionResponse.is_done` then
the message is edited via the :attr:`Interaction.message` using
:meth:`Message.edit` instead.
Raises
------
HTTPException
Editing the message failed.
InvalidArgument
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
TypeError
An object not of type :class:`File` was passed to ``file`` or ``files``.
HTTPException
Editing the message failed.
InvalidArgument
:attr:`Interaction.message` was ``None``, this may occur in a :class:`Thread`
or when the interaction is not a component or modal submit interaction.
Returns
-------
Optional[:class:`Message`]
The edited message. If the interaction has not yet been responded to,
:meth:`InteractionResponse.edit_message` is used which returns
a :class:`Message` or ``None`` corresponding to :attr:`Interaction.message`.
Otherwise, the :class:`Message` is returned via :meth:`Message.edit`.
"""
if not self.response.is_done():
return await self.response.edit_message(*args, **kwargs)
if self.message is not None:
return await self.message.edit(*args, **kwargs)
raise InvalidArgument(
"Interaction.message is None, this method can only be used in "
"response to a component or modal submit interaction."
)
class ApplicationNSFWChannelRequired(ApplicationCheckFailure):
"""Exception raised when a channel does not have the required NSFW setting.
This inherits from :exc:`~.ApplicationCheckFailure`.
Parameters
----------
channel: Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`PartialMessageable`]]
The channel that does not have NSFW enabled.
"""
def __init__(self, channel: Optional[Union[GuildChannel, Thread, PartialMessageable]]) -> None:
self.channel: Optional[Union[GuildChannel, Thread, PartialMessageable]] = channel
super().__init__(f"Channel '{channel}' needs to be NSFW for this command to work.")
The provided code snippet includes necessary dependencies for implementing the `is_nsfw` function. Write a Python function `def is_nsfw() -> AC` to solve the following problem:
A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.ApplicationNSFWChannelRequired` that is derived from :exc:`.ApplicationCheckFailure`. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.is_nsfw() async def ownercmd(interaction: Interaction): await interaction.response.send_message('Only NSFW channels!')
Here is the function:
def is_nsfw() -> AC:
"""A :func:`.check` that checks if the channel is a NSFW channel.
This check raises a special exception, :exc:`.ApplicationNSFWChannelRequired`
that is derived from :exc:`.ApplicationCheckFailure`.
Example
-------
.. code-block:: python3
@bot.slash_command()
@application_checks.is_nsfw()
async def ownercmd(interaction: Interaction):
await interaction.response.send_message('Only NSFW channels!')
"""
def pred(interaction: Interaction) -> bool:
ch = interaction.channel
if interaction.guild is None or (
isinstance(ch, (nextcord.TextChannel, nextcord.Thread)) and ch.is_nsfw()
):
return True
raise ApplicationNSFWChannelRequired(ch)
return check(pred) | A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.ApplicationNSFWChannelRequired` that is derived from :exc:`.ApplicationCheckFailure`. Example ------- .. code-block:: python3 @bot.slash_command() @application_checks.is_nsfw() async def ownercmd(interaction: Interaction): await interaction.response.send_message('Only NSFW channels!') |
160,931 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
class CallbackWrapper:
"""A class used to wrap a callback in a sane way to modify aspects of application commands.
By creating a decorator that makes this class wrap a function or an application command, you can easily modify
attributes of the command regardless if this wraps the callback or the application command, and without needing
to make the application command object interpret arbitrarily set function attributes.
The ``modify`` method must be overridden.
This handles both multiple layers of wrappers, or if it wraps around a :class:`BaseApplicationCommand`
Parameters
----------
callback: Union[Callable, :class:`CallbackWrapper`, :class:`BaseApplicationCommand`]
Callback, other callback wrapper, or application command to wrap and/or modify.
Examples
--------
Creating a decorator that makes the description of the command uppercase, and offers an "override" argument: ::
def upper_description(description_override: str = None):
class UpperDescription(CallbackWrapper):
def modify(self, app_cmd):
if description_override is not None:
app_cmd.description = description_override.upper()
elif app_cmd.description:
app_cmd.description = app_cmd.description.upper()
def wrapper(func):
return UpperDescription(func)
return wrapper
async def test(interaction):
await interaction.send("The description of this command should be in all uppercase!")
"""
def __new__(
cls,
callback: Union[
Callable, CallbackWrapper, BaseApplicationCommand, SlashApplicationSubcommand
],
*args,
**kwargs,
) -> Union[CallbackWrapper, BaseApplicationCommand, SlashApplicationSubcommand]:
wrapper = super(CallbackWrapper, cls).__new__(cls)
wrapper.__init__(callback, *args, **kwargs)
if isinstance(callback, (BaseApplicationCommand, SlashApplicationSubcommand)):
callback.modify_callbacks.extend(wrapper.modify_callbacks)
return callback
return wrapper
def __init__(self, callback: Union[Callable, CallbackWrapper], *args, **kwargs) -> None:
# noinspection PyTypeChecker
self.callback: Optional[Callable] = None
self.modify_callbacks: List[Callable] = [self.modify]
if isinstance(callback, CallbackWrapper):
self.callback = callback.callback
self.modify_callbacks += callback.modify_callbacks
else:
self.callback = callback
def modify(self, app_cmd: BaseApplicationCommand):
raise NotImplementedError
class BaseApplicationCommand(CallbackMixin, CallbackWrapperMixin):
"""Base class for all application commands.
Attributes
----------
checks: List[Union[Callable[[:class:`ClientCog`, :class:`Interaction`], MaybeCoro[:class:`bool`]], Callable[[:class:`Interaction`], MaybeCoro[:class:`bool`]]]]
A list of predicates that verifies if the command could be executed
with the given :class:`Interaction` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.ApplicationError` should be used. Note that if the checks fail then
:exc:`.ApplicationCheckFailure` exception is raised to the :func:`.on_application_command_error`
event.
"""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Base application command class that all specific application command classes should subclass. All common
behavior should be here, with subclasses either adding on or overriding specific aspects of this class.
Parameters
----------
cmd_type: :class:`ApplicationCommandType`
Type of application command. This should be set by subclasses.
name: :class:`str`
Name of the command.
description: :class:`str`
Description of the command.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the command for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :data:`~typing.Callable`
Callback to make the application command from, and to run when the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list/set/whatever of guild ID's that the application command should register to.
If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will
be used instead. If both of those are unset, then the command will be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
CallbackWrapperMixin.__init__(self, callback)
CallbackMixin.__init__(self, callback=callback, parent_cog=parent_cog)
self._state: Optional[ConnectionState] = None
self.type = cmd_type or ApplicationCommandType(1)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
self.use_default_guild_ids: bool = guild_ids is MISSING and not force_global
self.dm_permission: Optional[bool] = dm_permission
self.default_member_permissions: Optional[
Union[Permissions, int]
] = default_member_permissions
self.nsfw: bool = nsfw
self.force_global: bool = force_global
self.command_ids: Dict[Optional[int], int] = {}
"""
Dict[Optional[:class:`int`], :class:`int`]:
Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
"""
self.options: Dict[str, ApplicationCommandOption] = {}
# Simple-ish getter + setter methods.
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_guild_permissions", {})
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
.. versionadded:: 2.1
"""
return str(self.name)
def description(self) -> str:
"""The description the command should have in Discord. Should be 1-100 characters long."""
return self._description or DEFAULT_SLASH_DESCRIPTION
def description(self, new_description: str) -> None:
self._description = new_description
def is_guild(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be registered to any guilds."""
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
return bool(self.guild_ids_to_rollout or guild_only_ids)
def guild_ids(self) -> Set[int]:
"""Returns a :class:`set` containing all guild ID's this command is registered to."""
# TODO: Is this worthwhile?
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
# ignore explanation: Mypy says that guild_only_ids can contain None due to self.command_ids.keys() having
# None being typehinted, but we remove None before returning it.
return guild_only_ids # type: ignore
def add_guild_rollout(self, guild: Union[int, Guild]) -> None:
"""Adds a Guild to the command to be rolled out to when the rollout is run.
Parameters
----------
guild: Union[:class:`int`, :class:`Guild`]
Guild or Guild ID to add this command to roll out to.
"""
self.guild_ids_to_rollout.add(guild.id if isinstance(guild, Guild) else guild)
def is_global(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be a global command."""
return self.force_global or not self.is_guild or None in self.command_ids
def get_signature(
self, guild_id: Optional[int] = None
) -> Tuple[Optional[str], int, Optional[int]]:
"""Returns a command signature with the given guild ID.
Parameters
----------
guild_id: Optional[:class:`None`]
Guild ID to make the signature for. If set to ``None``, it acts as a global command signature.
Returns
-------
Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]
A tuple that acts as a signature made up of the name, type, and guild ID.
"""
# noinspection PyUnresolvedReferences
return self.name, self.type.value, guild_id
def get_rollout_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
for guild_id in self.guild_ids_to_rollout:
ret.add(self.get_signature(guild_id))
return ret
def get_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
if self.is_guild:
for guild_id in self.guild_ids:
ret.add(self.get_signature(guild_id))
return ret
def get_name_localization_payload(self) -> Optional[Dict[str, str]]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def get_default_member_permissions_value(self) -> Optional[int]:
if (
isinstance(self.default_member_permissions, int)
or self.default_member_permissions is None
):
return self.default_member_permissions
return self.default_member_permissions.value
def get_payload(self, guild_id: Optional[int]) -> dict:
"""Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
Parameters
----------
guild_id: Optional[:class:`int`]
Guild ID that this payload is for. If set to ``None``, it will be a global command payload instead.
Returns
-------
:class:`dict`
Dictionary payload to upsert to Discord.
"""
# Below is to make PyCharm stop complaining that self.type.value isn't valid.
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.default_member_permissions is not None:
# While Discord accepts it as an int, they will respond back with the permissions value as a string because
# the permissions bitfield can get too big for them. Stringify it for easy payload-comparison.
ret["default_member_permissions"] = str(self.get_default_member_permissions_value())
if guild_id: # Guild-command specific payload options.
ret["guild_id"] = guild_id
# Global command specific payload options.
elif self.dm_permission is not None:
ret["dm_permission"] = self.dm_permission
else:
# Discord seems to send back the DM permission as True regardless if we sent it or not, so we send as
# the default (True) to ensure payload parity for comparisons.
ret["dm_permission"] = True
ret["nsfw"] = self.nsfw
return ret
def parse_discord_response(
self,
state: ConnectionState,
data: Union[ApplicationCommandInteractionData, ApplicationCommandPayload],
) -> None:
"""Parses the application command creation/update response from Discord.
Parameters
----------
state: :class:`ConnectionState`
Connection state to use internally in the command.
data: Union[:class:`ApplicationCommandInteractionData`, :class:`ApplicationCommand`]
Raw dictionary data from Discord.
"""
self._state = state
command_id = int(data["id"])
if guild_id := data.get("guild_id", None):
guild_id = int(guild_id)
self.command_ids[guild_id] = command_id
self.guild_ids_to_rollout.add(guild_id)
else:
self.command_ids[None] = command_id
def is_payload_valid(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
"""Checks if the given raw application command interaction payload from Discord is possibly valid for
this command.
Note that while this may return ``True`` for a given payload, that doesn't mean that the payload is fully
correct for this command. Discord doesn't send data for parameters that are optional and aren't supplied by
the user.
Parameters
----------
raw_payload: :class:`dict`
Application command interaction payload from Discord.
guild_id: Optional[:class:`int`]
Guild ID that the payload is from. If it's from a global command, this should be ``None``
Returns
-------
:class:`bool`
``True`` if the given payload is possibly valid for this command. ``False`` otherwise.
"""
cmd_payload = self.get_payload(guild_id)
if cmd_payload.get("guild_id", 0) != int(raw_payload.get("guild_id", 0)):
_log.debug("Guild ID doesn't match raw payload, not valid payload.")
return False
if not check_dictionary_values(
cmd_payload,
raw_payload, # type: ignore # specificity of typeddicts doesnt matter in validation
"default_member_permissions",
"description",
"type",
"name",
"name_localizations",
"description_localizations",
"dm_permission",
"nsfw",
):
_log.debug("Failed check dictionary values, not valid payload.")
return False
if len(cmd_payload.get("options", [])) != len(raw_payload.get("options", [])):
_log.debug("Option amount between commands not equal, not valid payload.")
return False
for cmd_option in cmd_payload.get("options", []):
# I absolutely do not trust Discord or us ordering things nicely, so check through both.
found_correct_value = False
for raw_option in raw_payload.get("options", []):
if cmd_option["name"] == raw_option["name"]:
found_correct_value = True
# At this time, ApplicationCommand options are identical between locally-generated payloads and
# payloads from Discord. If that were to change, switch from a recursive setup and manually
# check_dictionary_values.
if not deep_dictionary_check(cmd_option, raw_option): # type: ignore
# its a dict check so typeddicts do not matter
_log.debug("Options failed deep dictionary checks, not valid payload.")
return False
break
if not found_correct_value:
_log.debug("Discord is missing an option we have, not valid payload.")
return False
return True
def is_interaction_valid(self, interaction: Interaction) -> bool:
"""Checks if the interaction given is possibly valid for this command.
If the command has more parameters (especially optionals) than the interaction coming in, this may cause a
desync between your bot and Discord.
Parameters
----------
interaction: :class:`Interaction`
Interaction to validate.
Returns
-------
:class:`bool`
``True`` If the interaction could possibly be for this command, ``False`` otherwise.
"""
data = interaction.data
if data is None:
raise ValueError("Discord did not provide us with interaction data")
our_payload = self.get_payload(data.get("guild_id", None))
def _recursive_subcommand_check(inter_pos: dict, cmd_pos: dict) -> bool:
"""A small recursive wrapper that checks for subcommand(s) (group(s)).
Parameters
----------
inter_pos: :class:`dict`
Current command position from the payload in the interaction.
cmd_pos: :class:`dict`
Current command position from the payload for the local command.
Returns
-------
:class:`bool`
``True`` if the payloads match, ``False`` otherwise.
"""
inter_options = inter_pos.get("options")
cmd_options = cmd_pos.get("options", {})
if inter_options is None:
raise ValueError("Interaction options was not provided")
our_options = {opt["name"]: opt for opt in cmd_options}
if (
len(inter_options) == 1
and ( # If the length is only 1, it might be a subcommand (group).
inter_options[0]["type"]
in (
ApplicationCommandOptionType.sub_command.value,
ApplicationCommandOptionType.sub_command_group.value,
)
)
and ( # This checks if it's a subcommand (group).
found_opt := our_options.get(
inter_options[0]["name"]
) # This checks if the name matches an option.
)
and inter_options[0]["type"] == found_opt["type"]
): # And this makes sure both are the same type.
return _recursive_subcommand_check(
inter_options[0], found_opt
) # If all of the above pass, recurse.
return _option_check(inter_options, cmd_options)
def _option_check(inter_options: dict, cmd_options: dict) -> bool:
"""Checks if the two given command payloads have matching options.
Parameters
----------
inter_options: :class:`dict`
Command option data from the interaction.
cmd_options: :class:`dict`
Command option data from the local command.
Returns
-------
:class:`bool`
``True`` if the options match, ``False`` otherwise.
"""
all_our_options = {}
required_options = {}
for our_opt in cmd_options:
all_our_options[our_opt["name"]] = our_opt
if our_opt.get("required"):
required_options[our_opt["name"]] = our_opt
all_inter_options = {inter_opt["name"]: inter_opt for inter_opt in inter_options}
if len(all_our_options) >= len(all_inter_options):
# If we have more options (including options) than the interaction, we are good to proceed.
all_our_options_copy = all_our_options.copy()
all_inter_options_copy = all_inter_options.copy()
# Begin checking required options.
for our_opt_name, our_opt in required_options.items():
if inter_opt := all_inter_options.get(our_opt_name):
if (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
all_our_options_copy.pop(our_opt_name)
all_inter_options_copy.pop(our_opt_name)
else:
_log.debug(
"%s Required option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter missing required option.", self.error_name)
return False # Required option wasn't found.
# Begin checking optional arguments.
for (
inter_opt_name,
inter_opt,
) in all_inter_options_copy.items(): # Should only contain optionals now.
if our_opt := all_our_options_copy.get(inter_opt_name):
if not (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
_log.debug(
"%s Optional option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter has option that we don't.", self.error_name)
return False # They have an option name that we don't.
else:
_log.debug(
"%s We have less options than them: %s vs %s",
self.error_name,
all_our_options,
all_inter_options,
)
return False # Interaction has more options than we do.
return True # No checks failed.
# caring about typeddict specificity will cause issues down the line
if not check_dictionary_values(our_payload, data, "name", "guild_id", "type"): # type: ignore
_log.debug("%s Failed basic dictionary check.", self.error_name)
return False
data_options = data.get("options")
payload_options = our_payload.get("options")
if data_options and payload_options:
return _recursive_subcommand_check(data, our_payload) # type: ignore
if data_options is None and payload_options is None:
return True # User and Message commands don't have options.
_log.debug(
"%s Mismatch between data and payload options: %s vs %s",
self.error_name,
data_options,
payload_options,
)
# There is a mismatch between the two, fail it.
return False
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = BaseCommandOption,
) -> None:
super().from_callback(callback=callback, option_class=option_class)
async def call_from_interaction(self, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, relying on the locally
stored :class:`ConnectionState` object.
Parameters
----------
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
await self.call(self._state, interaction) # type: ignore
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
raise NotImplementedError
def check_against_raw_payload(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
warnings.warn(
".check_against_raw_payload() is deprecated, please use .is_payload_valid instead.",
stacklevel=2,
category=FutureWarning,
)
return self.is_payload_valid(raw_payload, guild_id)
def get_guild_payload(self, guild_id: int):
warnings.warn(
".get_guild_payload is deprecated, use .get_payload(guild_id) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(guild_id)
def global_payload(self) -> dict:
warnings.warn(
".global_payload is deprecated, use .get_payload(None) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(None)
class SlashApplicationSubcommand(SlashCommandMixin, AutocompleteCommandMixin, CallbackWrapperMixin):
"""Class representing a subcommand or subcommand group of a slash command."""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandOptionType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
parent_cmd: Union[SlashApplicationCommand, SlashApplicationSubcommand, None] = None,
parent_cog: Optional[ClientCog] = None,
inherit_hooks: bool = False,
) -> None:
"""Slash Application Subcommand, supporting additional subcommands and autocomplete.
Parameters
----------
name: :class:`str`
Name of the subcommand (group). No capital letters or spaces. Defaults to the name of the callback.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized name as the value.
description: :class:`str`
Description of the subcommand (group). Must be between 1-100 characters. If not provided, a default value
will be given.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :class:`str`
Callback to create the command from, and run when the command is called. If provided, it
must be a coroutine. If this subcommand has subcommands, the callback will never be called.
parent_cmd: Union[:class:`SlashApplicationCommand`, :class:`SlashApplicationSubcommand`]
Parent (sub)command for this subcommand.
cmd_type: :class:`ApplicationCommandOptionType`
Should either be ``ApplicationCommandOptionType.sub_command`` or
``ApplicationCommandOptionType.sub_command_group``
parent_cog: Optional[:class:`ClientCog`]
Parent cog for the callback, if it exists. If provided, it will be given to the callback as ``self``.
inherit_hooks: :class:`bool`
If this subcommand should inherit the parent (sub)commands ``before_invoke`` and ``after_invoke`` callbacks.
Defaults to ``False``..
"""
SlashCommandMixin.__init__(self, callback=callback, parent_cog=parent_cog)
AutocompleteCommandMixin.__init__(self, parent_cog)
CallbackWrapperMixin.__init__(self, callback)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.type = cmd_type
self.parent_cmd = parent_cmd
self._inherit_hooks: bool = inherit_hooks
self.options: Dict[str, SlashCommandOption] = {}
def qualified_name(self) -> str:
""":class:`str`: Retrieve the command name including all parents space separated.
An example of the output would be ``parent group subcommand``.
.. versionadded:: 2.1
"""
return (
f"{self.parent_cmd.qualified_name} {self.name}" if self.parent_cmd else str(self.name)
)
async def call(
self,
state: ConnectionState,
interaction: Interaction,
option_data: Optional[List[ApplicationCommandInteractionDataOption]],
) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available and the given option data.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the subcommand.
option_data: List[:class:`dict`]
List of raw option data from Discord.
"""
if self.children and option_data is not None:
await self.children[option_data[0]["name"]].call(
state, interaction, option_data[0].get("options")
)
else:
await self.call_slash(state, interaction, option_data)
def get_name_localization_payload(self) -> Optional[dict]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def payload(self) -> dict:
"""Returns a dict payload made of the attributes of the subcommand (group) to be sent to Discord."""
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.children:
ret["options"] = [child.payload for child in self.children.values()]
elif self.options:
ret["options"] = [parameter.payload for parameter in self.options.values()]
return ret
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Type[SlashCommandOption] = SlashCommandOption,
call_children: bool = True,
) -> None:
SlashCommandMixin.from_callback(self, callback=callback, option_class=option_class)
if call_children:
for child in self.children.values():
child.from_callback(
callback=child.callback,
option_class=option_class,
call_children=call_children,
)
if self.error_callback is None:
self.error_callback = self.parent_cmd.error_callback if self.parent_cmd else None
if self._inherit_hooks and self.parent_cmd:
self.checks.extend(self.parent_cmd.checks)
self._callback_before_invoke = self.parent_cmd._callback_before_invoke
self._callback_after_invoke = self.parent_cmd._callback_after_invoke
super().from_autocomplete()
CallbackWrapperMixin.modify(self)
def subcommand(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
inherit_hooks: bool = False,
) -> Callable[[Callable], SlashApplicationSubcommand]:
"""Takes the decorated callback and turns it into a :class:`SlashApplicationSubcommand` added as a subcommand.
Parameters
----------
name: :class:`str`
Name of the command that users will see. If not set, it defaults to the name of the callback.
description: :class:`str`
Description of the command that users will see. If not specified, the docstring will be used.
If no docstring is found for the command callback, it defaults to "No description provided".
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
inherit_hooks: :class:`bool`
If the subcommand should inherit the parent subcommands ``before_invoke`` and ``after_invoke`` callbacks.
Defaults to ``False``.
"""
def decorator(func: Callable) -> SlashApplicationSubcommand:
ret = SlashApplicationSubcommand(
name=name,
name_localizations=name_localizations,
description=description,
description_localizations=description_localizations,
callback=func,
parent_cmd=self,
cmd_type=ApplicationCommandOptionType.sub_command,
parent_cog=self.parent_cog,
inherit_hooks=inherit_hooks,
)
self._children[
ret.name
or (func.callback.__name__ if isinstance(func, CallbackWrapper) else func.__name__)
] = ret
return ret
if isinstance(
self.parent_cmd, SlashApplicationSubcommand
): # Discord limitation, no groups in groups.
raise TypeError(
f"{self.error_name} Subcommand groups cannot be nested inside subcommand groups."
)
self.type = ApplicationCommandOptionType.sub_command_group
return decorator
def command_ids(self) -> Dict[Optional[int], int]:
"""Dict[Optional[:class:`int`], :class:`int`]: Command IDs the parent command of this subcommand currently has.
Schema: {Guild ID (None for global): command ID}
.. versionadded:: 2.2
"""
return self.parent_cmd.command_ids if self.parent_cmd else {}
The provided code snippet includes necessary dependencies for implementing the `application_command_before_invoke` function. Write a Python function `def application_command_before_invoke(coro) -> AC` to solve the following problem:
A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. Example ------- .. code-block:: python3 async def record_usage(interaction: Interaction): print( interaction.user, "used", interaction.application_command, "at", interaction.message.created_at ) @bot.slash_command() @application_checks.application_command_before_invoke(record_usage) async def who(interaction: Interaction): # Output: <User> used who at <Time> await interaction.response.send_message("I am a bot") class What(commands.Cog): @application_checks.application_command_before_invoke(record_usage) @nextcord.slash_command() async def when(self, interaction: Interaction): # Output: <User> used when at <Time> await interaction.response.send_message( f"and i have existed since {interaction.client.user.created_at}" ) @nextcord.slash_command() async def where(self, interaction: Interaction): # Output: <Nothing> await interaction.response.send_message("on Discord") @nextcord.slash_command() async def why(self, interaction: Interaction): # Output: <Nothing> await interaction.response.send_message("because someone made me") bot.add_cog(What())
Here is the function:
def application_command_before_invoke(coro) -> AC:
"""A decorator that registers a coroutine as a pre-invoke hook.
This allows you to refer to one before invoke hook for several commands that
do not have to be within the same cog.
Example
-------
.. code-block:: python3
async def record_usage(interaction: Interaction):
print(
interaction.user,
"used",
interaction.application_command,
"at",
interaction.message.created_at
)
@bot.slash_command()
@application_checks.application_command_before_invoke(record_usage)
async def who(interaction: Interaction): # Output: <User> used who at <Time>
await interaction.response.send_message("I am a bot")
class What(commands.Cog):
@application_checks.application_command_before_invoke(record_usage)
@nextcord.slash_command()
async def when(self, interaction: Interaction):
# Output: <User> used when at <Time>
await interaction.response.send_message(
f"and i have existed since {interaction.client.user.created_at}"
)
@nextcord.slash_command()
async def where(self, interaction: Interaction): # Output: <Nothing>
await interaction.response.send_message("on Discord")
@nextcord.slash_command()
async def why(self, interaction: Interaction): # Output: <Nothing>
await interaction.response.send_message("because someone made me")
bot.add_cog(What())
"""
class BeforeInvokeModifier(CallbackWrapper):
def modify(self, app_cmd: BaseApplicationCommand) -> None:
app_cmd._callback_before_invoke = coro
def decorator(
func: Union[SlashApplicationSubcommand, BaseApplicationCommand, "CoroFunc"]
) -> Union[SlashApplicationSubcommand, BaseApplicationCommand, BeforeInvokeModifier]:
return BeforeInvokeModifier(func)
return decorator # type: ignore | A decorator that registers a coroutine as a pre-invoke hook. This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog. Example ------- .. code-block:: python3 async def record_usage(interaction: Interaction): print( interaction.user, "used", interaction.application_command, "at", interaction.message.created_at ) @bot.slash_command() @application_checks.application_command_before_invoke(record_usage) async def who(interaction: Interaction): # Output: <User> used who at <Time> await interaction.response.send_message("I am a bot") class What(commands.Cog): @application_checks.application_command_before_invoke(record_usage) @nextcord.slash_command() async def when(self, interaction: Interaction): # Output: <User> used when at <Time> await interaction.response.send_message( f"and i have existed since {interaction.client.user.created_at}" ) @nextcord.slash_command() async def where(self, interaction: Interaction): # Output: <Nothing> await interaction.response.send_message("on Discord") @nextcord.slash_command() async def why(self, interaction: Interaction): # Output: <Nothing> await interaction.response.send_message("because someone made me") bot.add_cog(What()) |
160,932 | from __future__ import annotations
import asyncio
import functools
from typing import TYPE_CHECKING, Callable, Dict, Union
import nextcord
from nextcord.application_command import (
BaseApplicationCommand,
CallbackWrapper,
SlashApplicationSubcommand,
)
from nextcord.interactions import Interaction
from .errors import (
ApplicationBotMissingAnyRole,
ApplicationBotMissingPermissions,
ApplicationBotMissingRole,
ApplicationCheckAnyFailure,
ApplicationCheckFailure,
ApplicationCheckForBotOnly,
ApplicationMissingAnyRole,
ApplicationMissingPermissions,
ApplicationMissingRole,
ApplicationNoPrivateMessage,
ApplicationNotOwner,
ApplicationNSFWChannelRequired,
ApplicationPrivateMessageOnly,
)
class CallbackWrapper:
"""A class used to wrap a callback in a sane way to modify aspects of application commands.
By creating a decorator that makes this class wrap a function or an application command, you can easily modify
attributes of the command regardless if this wraps the callback or the application command, and without needing
to make the application command object interpret arbitrarily set function attributes.
The ``modify`` method must be overridden.
This handles both multiple layers of wrappers, or if it wraps around a :class:`BaseApplicationCommand`
Parameters
----------
callback: Union[Callable, :class:`CallbackWrapper`, :class:`BaseApplicationCommand`]
Callback, other callback wrapper, or application command to wrap and/or modify.
Examples
--------
Creating a decorator that makes the description of the command uppercase, and offers an "override" argument: ::
def upper_description(description_override: str = None):
class UpperDescription(CallbackWrapper):
def modify(self, app_cmd):
if description_override is not None:
app_cmd.description = description_override.upper()
elif app_cmd.description:
app_cmd.description = app_cmd.description.upper()
def wrapper(func):
return UpperDescription(func)
return wrapper
async def test(interaction):
await interaction.send("The description of this command should be in all uppercase!")
"""
def __new__(
cls,
callback: Union[
Callable, CallbackWrapper, BaseApplicationCommand, SlashApplicationSubcommand
],
*args,
**kwargs,
) -> Union[CallbackWrapper, BaseApplicationCommand, SlashApplicationSubcommand]:
wrapper = super(CallbackWrapper, cls).__new__(cls)
wrapper.__init__(callback, *args, **kwargs)
if isinstance(callback, (BaseApplicationCommand, SlashApplicationSubcommand)):
callback.modify_callbacks.extend(wrapper.modify_callbacks)
return callback
return wrapper
def __init__(self, callback: Union[Callable, CallbackWrapper], *args, **kwargs) -> None:
# noinspection PyTypeChecker
self.callback: Optional[Callable] = None
self.modify_callbacks: List[Callable] = [self.modify]
if isinstance(callback, CallbackWrapper):
self.callback = callback.callback
self.modify_callbacks += callback.modify_callbacks
else:
self.callback = callback
def modify(self, app_cmd: BaseApplicationCommand):
raise NotImplementedError
class BaseApplicationCommand(CallbackMixin, CallbackWrapperMixin):
"""Base class for all application commands.
Attributes
----------
checks: List[Union[Callable[[:class:`ClientCog`, :class:`Interaction`], MaybeCoro[:class:`bool`]], Callable[[:class:`Interaction`], MaybeCoro[:class:`bool`]]]]
A list of predicates that verifies if the command could be executed
with the given :class:`Interaction` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.ApplicationError` should be used. Note that if the checks fail then
:exc:`.ApplicationCheckFailure` exception is raised to the :func:`.on_application_command_error`
event.
"""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
guild_ids: Optional[Iterable[int]] = MISSING,
dm_permission: Optional[bool] = None,
default_member_permissions: Optional[Union[Permissions, int]] = None,
nsfw: bool = False,
parent_cog: Optional[ClientCog] = None,
force_global: bool = False,
) -> None:
"""Base application command class that all specific application command classes should subclass. All common
behavior should be here, with subclasses either adding on or overriding specific aspects of this class.
Parameters
----------
cmd_type: :class:`ApplicationCommandType`
Type of application command. This should be set by subclasses.
name: :class:`str`
Name of the command.
description: :class:`str`
Description of the command.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the command for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :data:`~typing.Callable`
Callback to make the application command from, and to run when the application command is called.
guild_ids: Iterable[:class:`int`]
An iterable list/set/whatever of guild ID's that the application command should register to.
If not passed and :attr:`Client.default_guild_ids` is set, then those default guild ids will
be used instead. If both of those are unset, then the command will be a global command.
dm_permission: :class:`bool`
If the command should be usable in DMs or not. Setting to ``False`` will disable the command from being
usable in DMs. Only for global commands, but will not error on guild.
default_member_permissions: Optional[Union[:class:`Permissions`, :class:`int`]]
Permission(s) required to use the command. Inputting ``8`` or ``Permissions(administrator=True)`` for
example will only allow Administrators to use the command. If set to 0, nobody will be able to use it by
default. Server owners CAN override the permission requirements.
nsfw: :class:`bool`
Whether the command can only be used in age-restricted channels. Defaults to ``False``.
.. versionadded:: 2.4
parent_cog: Optional[:class:`ClientCog`]
``ClientCog`` to forward to the callback as the ``self`` argument.
force_global: :class:`bool`
If this command should be registered as a global command, ALONG WITH all guild IDs set.
"""
CallbackWrapperMixin.__init__(self, callback)
CallbackMixin.__init__(self, callback=callback, parent_cog=parent_cog)
self._state: Optional[ConnectionState] = None
self.type = cmd_type or ApplicationCommandType(1)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
self.use_default_guild_ids: bool = guild_ids is MISSING and not force_global
self.dm_permission: Optional[bool] = dm_permission
self.default_member_permissions: Optional[
Union[Permissions, int]
] = default_member_permissions
self.nsfw: bool = nsfw
self.force_global: bool = force_global
self.command_ids: Dict[Optional[int], int] = {}
"""
Dict[Optional[:class:`int`], :class:`int`]:
Command IDs that this application command currently has. Schema: {Guild ID (None for global): command ID}
"""
self.options: Dict[str, ApplicationCommandOption] = {}
# Simple-ish getter + setter methods.
def required_permissions(self) -> Dict[str, bool]:
"""Returns the permissions required to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_permissions", {})
def required_bot_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_permissions", {})
def required_guild_permissions(self) -> Dict[str, bool]:
"""Returns the guild permissions needed to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_guild_permissions", {})
def required_bot_guild_permissions(self) -> Dict[str, bool]:
"""Returns the permissions the bot needs to have in this guild in order to run this command.
.. note::
This returns the permissions set with :func:`ext.application_checks.bot_has_guild_permissions`.
.. versionadded:: 2.6
Returns
-------
Dict[:class:`str`, :class:`bool`]
A dictionary of the required permissions for this command.
"""
return getattr(self.callback, "__slash_required_bot_guild_permissions", {})
def qualified_name(self) -> str:
""":class:`str`: Retrieves the fully qualified command name.
.. versionadded:: 2.1
"""
return str(self.name)
def description(self) -> str:
"""The description the command should have in Discord. Should be 1-100 characters long."""
return self._description or DEFAULT_SLASH_DESCRIPTION
def description(self, new_description: str) -> None:
self._description = new_description
def is_guild(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be registered to any guilds."""
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
return bool(self.guild_ids_to_rollout or guild_only_ids)
def guild_ids(self) -> Set[int]:
"""Returns a :class:`set` containing all guild ID's this command is registered to."""
# TODO: Is this worthwhile?
guild_only_ids = set(self.command_ids.keys())
guild_only_ids.discard(None)
# ignore explanation: Mypy says that guild_only_ids can contain None due to self.command_ids.keys() having
# None being typehinted, but we remove None before returning it.
return guild_only_ids # type: ignore
def add_guild_rollout(self, guild: Union[int, Guild]) -> None:
"""Adds a Guild to the command to be rolled out to when the rollout is run.
Parameters
----------
guild: Union[:class:`int`, :class:`Guild`]
Guild or Guild ID to add this command to roll out to.
"""
self.guild_ids_to_rollout.add(guild.id if isinstance(guild, Guild) else guild)
def is_global(self) -> bool:
""":class:`bool`: Returns ``True`` if this command is or should be a global command."""
return self.force_global or not self.is_guild or None in self.command_ids
def get_signature(
self, guild_id: Optional[int] = None
) -> Tuple[Optional[str], int, Optional[int]]:
"""Returns a command signature with the given guild ID.
Parameters
----------
guild_id: Optional[:class:`None`]
Guild ID to make the signature for. If set to ``None``, it acts as a global command signature.
Returns
-------
Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]
A tuple that acts as a signature made up of the name, type, and guild ID.
"""
# noinspection PyUnresolvedReferences
return self.name, self.type.value, guild_id
def get_rollout_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all signatures that this command wants to roll out to.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
for guild_id in self.guild_ids_to_rollout:
ret.add(self.get_signature(guild_id))
return ret
def get_signatures(self) -> Set[Tuple[str, int, Optional[int]]]:
"""Returns all the signatures that this command has.
Command signatures are made up of the command name, command type, and Guild ID (``None`` for global).
Returns
-------
Set[Tuple[:class:`str`, :class:`int`, Optional[:class:`int`]]]
A set of tuples that act as signatures.
"""
ret = set()
if self.is_global:
ret.add(self.get_signature(None))
if self.is_guild:
for guild_id in self.guild_ids:
ret.add(self.get_signature(guild_id))
return ret
def get_name_localization_payload(self) -> Optional[Dict[str, str]]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def get_default_member_permissions_value(self) -> Optional[int]:
if (
isinstance(self.default_member_permissions, int)
or self.default_member_permissions is None
):
return self.default_member_permissions
return self.default_member_permissions.value
def get_payload(self, guild_id: Optional[int]) -> dict:
"""Makes an Application Command payload for this command to upsert to Discord with the given Guild ID.
Parameters
----------
guild_id: Optional[:class:`int`]
Guild ID that this payload is for. If set to ``None``, it will be a global command payload instead.
Returns
-------
:class:`dict`
Dictionary payload to upsert to Discord.
"""
# Below is to make PyCharm stop complaining that self.type.value isn't valid.
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.default_member_permissions is not None:
# While Discord accepts it as an int, they will respond back with the permissions value as a string because
# the permissions bitfield can get too big for them. Stringify it for easy payload-comparison.
ret["default_member_permissions"] = str(self.get_default_member_permissions_value())
if guild_id: # Guild-command specific payload options.
ret["guild_id"] = guild_id
# Global command specific payload options.
elif self.dm_permission is not None:
ret["dm_permission"] = self.dm_permission
else:
# Discord seems to send back the DM permission as True regardless if we sent it or not, so we send as
# the default (True) to ensure payload parity for comparisons.
ret["dm_permission"] = True
ret["nsfw"] = self.nsfw
return ret
def parse_discord_response(
self,
state: ConnectionState,
data: Union[ApplicationCommandInteractionData, ApplicationCommandPayload],
) -> None:
"""Parses the application command creation/update response from Discord.
Parameters
----------
state: :class:`ConnectionState`
Connection state to use internally in the command.
data: Union[:class:`ApplicationCommandInteractionData`, :class:`ApplicationCommand`]
Raw dictionary data from Discord.
"""
self._state = state
command_id = int(data["id"])
if guild_id := data.get("guild_id", None):
guild_id = int(guild_id)
self.command_ids[guild_id] = command_id
self.guild_ids_to_rollout.add(guild_id)
else:
self.command_ids[None] = command_id
def is_payload_valid(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
"""Checks if the given raw application command interaction payload from Discord is possibly valid for
this command.
Note that while this may return ``True`` for a given payload, that doesn't mean that the payload is fully
correct for this command. Discord doesn't send data for parameters that are optional and aren't supplied by
the user.
Parameters
----------
raw_payload: :class:`dict`
Application command interaction payload from Discord.
guild_id: Optional[:class:`int`]
Guild ID that the payload is from. If it's from a global command, this should be ``None``
Returns
-------
:class:`bool`
``True`` if the given payload is possibly valid for this command. ``False`` otherwise.
"""
cmd_payload = self.get_payload(guild_id)
if cmd_payload.get("guild_id", 0) != int(raw_payload.get("guild_id", 0)):
_log.debug("Guild ID doesn't match raw payload, not valid payload.")
return False
if not check_dictionary_values(
cmd_payload,
raw_payload, # type: ignore # specificity of typeddicts doesnt matter in validation
"default_member_permissions",
"description",
"type",
"name",
"name_localizations",
"description_localizations",
"dm_permission",
"nsfw",
):
_log.debug("Failed check dictionary values, not valid payload.")
return False
if len(cmd_payload.get("options", [])) != len(raw_payload.get("options", [])):
_log.debug("Option amount between commands not equal, not valid payload.")
return False
for cmd_option in cmd_payload.get("options", []):
# I absolutely do not trust Discord or us ordering things nicely, so check through both.
found_correct_value = False
for raw_option in raw_payload.get("options", []):
if cmd_option["name"] == raw_option["name"]:
found_correct_value = True
# At this time, ApplicationCommand options are identical between locally-generated payloads and
# payloads from Discord. If that were to change, switch from a recursive setup and manually
# check_dictionary_values.
if not deep_dictionary_check(cmd_option, raw_option): # type: ignore
# its a dict check so typeddicts do not matter
_log.debug("Options failed deep dictionary checks, not valid payload.")
return False
break
if not found_correct_value:
_log.debug("Discord is missing an option we have, not valid payload.")
return False
return True
def is_interaction_valid(self, interaction: Interaction) -> bool:
"""Checks if the interaction given is possibly valid for this command.
If the command has more parameters (especially optionals) than the interaction coming in, this may cause a
desync between your bot and Discord.
Parameters
----------
interaction: :class:`Interaction`
Interaction to validate.
Returns
-------
:class:`bool`
``True`` If the interaction could possibly be for this command, ``False`` otherwise.
"""
data = interaction.data
if data is None:
raise ValueError("Discord did not provide us with interaction data")
our_payload = self.get_payload(data.get("guild_id", None))
def _recursive_subcommand_check(inter_pos: dict, cmd_pos: dict) -> bool:
"""A small recursive wrapper that checks for subcommand(s) (group(s)).
Parameters
----------
inter_pos: :class:`dict`
Current command position from the payload in the interaction.
cmd_pos: :class:`dict`
Current command position from the payload for the local command.
Returns
-------
:class:`bool`
``True`` if the payloads match, ``False`` otherwise.
"""
inter_options = inter_pos.get("options")
cmd_options = cmd_pos.get("options", {})
if inter_options is None:
raise ValueError("Interaction options was not provided")
our_options = {opt["name"]: opt for opt in cmd_options}
if (
len(inter_options) == 1
and ( # If the length is only 1, it might be a subcommand (group).
inter_options[0]["type"]
in (
ApplicationCommandOptionType.sub_command.value,
ApplicationCommandOptionType.sub_command_group.value,
)
)
and ( # This checks if it's a subcommand (group).
found_opt := our_options.get(
inter_options[0]["name"]
) # This checks if the name matches an option.
)
and inter_options[0]["type"] == found_opt["type"]
): # And this makes sure both are the same type.
return _recursive_subcommand_check(
inter_options[0], found_opt
) # If all of the above pass, recurse.
return _option_check(inter_options, cmd_options)
def _option_check(inter_options: dict, cmd_options: dict) -> bool:
"""Checks if the two given command payloads have matching options.
Parameters
----------
inter_options: :class:`dict`
Command option data from the interaction.
cmd_options: :class:`dict`
Command option data from the local command.
Returns
-------
:class:`bool`
``True`` if the options match, ``False`` otherwise.
"""
all_our_options = {}
required_options = {}
for our_opt in cmd_options:
all_our_options[our_opt["name"]] = our_opt
if our_opt.get("required"):
required_options[our_opt["name"]] = our_opt
all_inter_options = {inter_opt["name"]: inter_opt for inter_opt in inter_options}
if len(all_our_options) >= len(all_inter_options):
# If we have more options (including options) than the interaction, we are good to proceed.
all_our_options_copy = all_our_options.copy()
all_inter_options_copy = all_inter_options.copy()
# Begin checking required options.
for our_opt_name, our_opt in required_options.items():
if inter_opt := all_inter_options.get(our_opt_name):
if (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
all_our_options_copy.pop(our_opt_name)
all_inter_options_copy.pop(our_opt_name)
else:
_log.debug(
"%s Required option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter missing required option.", self.error_name)
return False # Required option wasn't found.
# Begin checking optional arguments.
for (
inter_opt_name,
inter_opt,
) in all_inter_options_copy.items(): # Should only contain optionals now.
if our_opt := all_our_options_copy.get(inter_opt_name):
if not (
inter_opt["name"] == our_opt["name"]
and inter_opt["type"] == our_opt["type"]
):
_log.debug(
"%s Optional option don't match name and/or type.", self.error_name
)
return False # Options don't match name and/or type.
else:
_log.debug("%s Inter has option that we don't.", self.error_name)
return False # They have an option name that we don't.
else:
_log.debug(
"%s We have less options than them: %s vs %s",
self.error_name,
all_our_options,
all_inter_options,
)
return False # Interaction has more options than we do.
return True # No checks failed.
# caring about typeddict specificity will cause issues down the line
if not check_dictionary_values(our_payload, data, "name", "guild_id", "type"): # type: ignore
_log.debug("%s Failed basic dictionary check.", self.error_name)
return False
data_options = data.get("options")
payload_options = our_payload.get("options")
if data_options and payload_options:
return _recursive_subcommand_check(data, our_payload) # type: ignore
if data_options is None and payload_options is None:
return True # User and Message commands don't have options.
_log.debug(
"%s Mismatch between data and payload options: %s vs %s",
self.error_name,
data_options,
payload_options,
)
# There is a mismatch between the two, fail it.
return False
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Optional[Type[BaseCommandOption]] = BaseCommandOption,
) -> None:
super().from_callback(callback=callback, option_class=option_class)
async def call_from_interaction(self, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, relying on the locally
stored :class:`ConnectionState` object.
Parameters
----------
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
await self.call(self._state, interaction) # type: ignore
async def call(self, state: ConnectionState, interaction: Interaction) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the command.
"""
raise NotImplementedError
def check_against_raw_payload(
self, raw_payload: ApplicationCommandPayload, guild_id: Optional[int] = None
) -> bool:
warnings.warn(
".check_against_raw_payload() is deprecated, please use .is_payload_valid instead.",
stacklevel=2,
category=FutureWarning,
)
return self.is_payload_valid(raw_payload, guild_id)
def get_guild_payload(self, guild_id: int):
warnings.warn(
".get_guild_payload is deprecated, use .get_payload(guild_id) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(guild_id)
def global_payload(self) -> dict:
warnings.warn(
".global_payload is deprecated, use .get_payload(None) instead.",
stacklevel=2,
category=FutureWarning,
)
return self.get_payload(None)
class SlashApplicationSubcommand(SlashCommandMixin, AutocompleteCommandMixin, CallbackWrapperMixin):
"""Class representing a subcommand or subcommand group of a slash command."""
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
cmd_type: ApplicationCommandOptionType,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
callback: Optional[Callable] = None,
parent_cmd: Union[SlashApplicationCommand, SlashApplicationSubcommand, None] = None,
parent_cog: Optional[ClientCog] = None,
inherit_hooks: bool = False,
) -> None:
"""Slash Application Subcommand, supporting additional subcommands and autocomplete.
Parameters
----------
name: :class:`str`
Name of the subcommand (group). No capital letters or spaces. Defaults to the name of the callback.
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized name as the value.
description: :class:`str`
Description of the subcommand (group). Must be between 1-100 characters. If not provided, a default value
will be given.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
callback: :class:`str`
Callback to create the command from, and run when the command is called. If provided, it
must be a coroutine. If this subcommand has subcommands, the callback will never be called.
parent_cmd: Union[:class:`SlashApplicationCommand`, :class:`SlashApplicationSubcommand`]
Parent (sub)command for this subcommand.
cmd_type: :class:`ApplicationCommandOptionType`
Should either be ``ApplicationCommandOptionType.sub_command`` or
``ApplicationCommandOptionType.sub_command_group``
parent_cog: Optional[:class:`ClientCog`]
Parent cog for the callback, if it exists. If provided, it will be given to the callback as ``self``.
inherit_hooks: :class:`bool`
If this subcommand should inherit the parent (sub)commands ``before_invoke`` and ``after_invoke`` callbacks.
Defaults to ``False``..
"""
SlashCommandMixin.__init__(self, callback=callback, parent_cog=parent_cog)
AutocompleteCommandMixin.__init__(self, parent_cog)
CallbackWrapperMixin.__init__(self, callback)
self.name: Optional[str] = name
self.name_localizations: Optional[Dict[Union[str, Locale], str]] = name_localizations
self._description: Optional[str] = description
self.description_localizations: Optional[
Dict[Union[str, Locale], str]
] = description_localizations
self.type = cmd_type
self.parent_cmd = parent_cmd
self._inherit_hooks: bool = inherit_hooks
self.options: Dict[str, SlashCommandOption] = {}
def qualified_name(self) -> str:
""":class:`str`: Retrieve the command name including all parents space separated.
An example of the output would be ``parent group subcommand``.
.. versionadded:: 2.1
"""
return (
f"{self.parent_cmd.qualified_name} {self.name}" if self.parent_cmd else str(self.name)
)
async def call(
self,
state: ConnectionState,
interaction: Interaction,
option_data: Optional[List[ApplicationCommandInteractionDataOption]],
) -> None:
"""|coro|
Calls the callback via the given :class:`Interaction`, using the given :class:`ConnectionState` to get resolved
objects if needed and available and the given option data.
Parameters
----------
state: :class:`ConnectionState`
State object to get resolved objects from.
interaction: :class:`Interaction`
Interaction corresponding to the use of the subcommand.
option_data: List[:class:`dict`]
List of raw option data from Discord.
"""
if self.children and option_data is not None:
await self.children[option_data[0]["name"]].call(
state, interaction, option_data[0].get("options")
)
else:
await self.call_slash(state, interaction, option_data)
def get_name_localization_payload(self) -> Optional[dict]:
if self.name_localizations:
ret = {}
for locale, name in self.name_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = name
else:
ret[locale] = name
return ret
return None
def get_description_localization_payload(self) -> Optional[dict]:
if self.description_localizations:
ret = {}
for locale, description in self.description_localizations.items():
if isinstance(locale, Locale):
# noinspection PyUnresolvedReferences
ret[locale.value] = description
else:
ret[locale] = description
return ret
return None
def payload(self) -> dict:
"""Returns a dict payload made of the attributes of the subcommand (group) to be sent to Discord."""
# noinspection PyUnresolvedReferences
ret = {
"type": self.type.value,
"name": str(
self.name
), # Might as well stringify the name, will come in handy if people try using numbers.
"description": str(self.description), # Might as well do the same with the description.
"name_localizations": self.get_name_localization_payload(),
"description_localizations": self.get_description_localization_payload(),
}
if self.children:
ret["options"] = [child.payload for child in self.children.values()]
elif self.options:
ret["options"] = [parameter.payload for parameter in self.options.values()]
return ret
def from_callback(
self,
callback: Optional[Callable] = None,
option_class: Type[SlashCommandOption] = SlashCommandOption,
call_children: bool = True,
) -> None:
SlashCommandMixin.from_callback(self, callback=callback, option_class=option_class)
if call_children:
for child in self.children.values():
child.from_callback(
callback=child.callback,
option_class=option_class,
call_children=call_children,
)
if self.error_callback is None:
self.error_callback = self.parent_cmd.error_callback if self.parent_cmd else None
if self._inherit_hooks and self.parent_cmd:
self.checks.extend(self.parent_cmd.checks)
self._callback_before_invoke = self.parent_cmd._callback_before_invoke
self._callback_after_invoke = self.parent_cmd._callback_after_invoke
super().from_autocomplete()
CallbackWrapperMixin.modify(self)
def subcommand(
self,
name: Optional[str] = None,
description: Optional[str] = None,
*,
name_localizations: Optional[Dict[Union[Locale, str], str]] = None,
description_localizations: Optional[Dict[Union[Locale, str], str]] = None,
inherit_hooks: bool = False,
) -> Callable[[Callable], SlashApplicationSubcommand]:
"""Takes the decorated callback and turns it into a :class:`SlashApplicationSubcommand` added as a subcommand.
Parameters
----------
name: :class:`str`
Name of the command that users will see. If not set, it defaults to the name of the callback.
description: :class:`str`
Description of the command that users will see. If not specified, the docstring will be used.
If no docstring is found for the command callback, it defaults to "No description provided".
name_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Name(s) of the command for users of specific locales. The locale code should be the key, with the localized
name as the value.
description_localizations: Dict[Union[:class:`Locale`, :class:`str`], :class:`str`]
Description(s) of the subcommand for users of specific locales. The locale code should be the key, with the
localized description as the value.
inherit_hooks: :class:`bool`
If the subcommand should inherit the parent subcommands ``before_invoke`` and ``after_invoke`` callbacks.
Defaults to ``False``.
"""
def decorator(func: Callable) -> SlashApplicationSubcommand:
ret = SlashApplicationSubcommand(
name=name,
name_localizations=name_localizations,
description=description,
description_localizations=description_localizations,
callback=func,
parent_cmd=self,
cmd_type=ApplicationCommandOptionType.sub_command,
parent_cog=self.parent_cog,
inherit_hooks=inherit_hooks,
)
self._children[
ret.name
or (func.callback.__name__ if isinstance(func, CallbackWrapper) else func.__name__)
] = ret
return ret
if isinstance(
self.parent_cmd, SlashApplicationSubcommand
): # Discord limitation, no groups in groups.
raise TypeError(
f"{self.error_name} Subcommand groups cannot be nested inside subcommand groups."
)
self.type = ApplicationCommandOptionType.sub_command_group
return decorator
def command_ids(self) -> Dict[Optional[int], int]:
"""Dict[Optional[:class:`int`], :class:`int`]: Command IDs the parent command of this subcommand currently has.
Schema: {Guild ID (None for global): command ID}
.. versionadded:: 2.2
"""
return self.parent_cmd.command_ids if self.parent_cmd else {}
The provided code snippet includes necessary dependencies for implementing the `application_command_after_invoke` function. Write a Python function `def application_command_after_invoke(coro) -> AC` to solve the following problem:
A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.
Here is the function:
def application_command_after_invoke(coro) -> AC:
"""A decorator that registers a coroutine as a post-invoke hook.
This allows you to refer to one after invoke hook for several commands that
do not have to be within the same cog.
"""
class AfterInvokeModifier(CallbackWrapper):
def modify(self, app_cmd: BaseApplicationCommand) -> None:
app_cmd._callback_after_invoke = coro
def decorator(
func: Union[SlashApplicationSubcommand, BaseApplicationCommand, "CoroFunc"]
) -> Union[SlashApplicationSubcommand, BaseApplicationCommand, AfterInvokeModifier]:
return AfterInvokeModifier(func)
return decorator # type: ignore | A decorator that registers a coroutine as a post-invoke hook. This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog. |
160,933 | from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, overload
from .asset import Asset
from .colour import Colour
from .enums import ActivityType, try_enum
from .partial_emoji import PartialEmoji
from .utils import get_as_snowflake
ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify]
class ConnectionState:
if TYPE_CHECKING:
_get_websocket: Callable[..., DiscordWebSocket]
_get_client: Callable[..., Client]
_parsers: Dict[str, Callable[[Dict[str, Any]], None]]
def __init__(
self,
*,
dispatch: Callable,
handlers: Dict[str, Callable],
hooks: Dict[str, Callable],
http: HTTPClient,
loop: asyncio.AbstractEventLoop,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Status] = None,
intents: Intents = Intents.default(),
chunk_guilds_at_startup: bool = MISSING,
member_cache_flags: MemberCacheFlags = MISSING,
) -> None:
self.loop: asyncio.AbstractEventLoop = loop
self.http: HTTPClient = http
self.max_messages: Optional[int] = max_messages
if self.max_messages is not None and self.max_messages <= 0:
self.max_messages = 1000
self.dispatch: Callable = dispatch
self.handlers: Dict[str, Callable] = handlers
self.hooks: Dict[str, Callable] = hooks
self.shard_count: Optional[int] = None
self._ready_task: Optional[asyncio.Task] = None
self.application_id: Optional[int] = application_id
self.heartbeat_timeout: float = heartbeat_timeout
self.guild_ready_timeout: float = guild_ready_timeout
if self.guild_ready_timeout < 0:
raise ValueError("guild_ready_timeout cannot be negative")
if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):
raise TypeError("allowed_mentions parameter must be AllowedMentions")
self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions
self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}
self._chunk_tasks: Dict[Union[int, str], asyncio.Task[None]] = {}
self._background_tasks: Set[asyncio.Task] = set()
if activity is not None:
if not isinstance(activity, BaseActivity):
raise TypeError("activity parameter must derive from BaseActivity.")
raw_activity = activity.to_dict()
else:
raw_activity = activity
raw_status = ("invisible" if status is Status.offline else str(status)) if status else None
if not isinstance(intents, Intents):
raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
if not intents.guilds:
_log.warning("Guilds intent seems to be disabled. This may cause state related issues.")
if chunk_guilds_at_startup is MISSING:
chunk_guilds_at_startup = intents.members
self._chunk_guilds: bool = chunk_guilds_at_startup
# Ensure these two are set properly
if not intents.members and self._chunk_guilds:
raise ValueError("Intents.members must be enabled to chunk guilds at startup.")
if member_cache_flags is MISSING:
member_cache_flags = MemberCacheFlags.from_intents(intents)
else:
if not isinstance(member_cache_flags, MemberCacheFlags):
raise TypeError(
"member_cache_flags parameter must be MemberCacheFlags "
f"not {type(member_cache_flags)!r}"
)
member_cache_flags._verify_intents(intents)
self.member_cache_flags: MemberCacheFlags = member_cache_flags
self._activity: Optional[ActivityPayload] = raw_activity
self._status: Optional[str] = raw_status
self._intents: Intents = intents
# A set of all application command objects available. Set because duplicates should not exist.
self._application_commands: Set[BaseApplicationCommand] = set()
# A dictionary of all available unique command signatures. Compiled at runtime because needing to iterate
# through all application commands would take far more time. If memory is problematic, perhaps this can go?
self._application_command_signatures: Dict[
Tuple[Optional[str], int, Optional[int]], BaseApplicationCommand
] = {}
# A dictionary of Discord Application Command ID's and the ApplicationCommand object they correspond to.
self._application_command_ids: Dict[int, BaseApplicationCommand] = {}
if not intents.members or member_cache_flags._empty:
self.store_user = self.create_user
self.deref_user = self.deref_user_no_intents
self.parsers = parsers = {}
for attr, func in inspect.getmembers(self):
if attr.startswith("parse_"):
parsers[attr[6:].upper()] = func
self.clear()
def clear(self, *, views: bool = True, modals: bool = True) -> None:
self.user: Optional[ClientUser] = None
# Originally, this code used WeakValueDictionary to maintain references to the
# global user mapping.
# However, profiling showed that this came with two cons:
# 1. The __weakref__ slot caused a non-trivial increase in memory
# 2. The performance of the mapping caused store_user to be a bottleneck.
# Since this is undesirable, a mapping is now used instead with stored
# references now using a regular dictionary with eviction being done
# using __del__. Testing this for memory leaks led to no discernible leaks,
# though more testing will have to be done.
self._users: Dict[int, User] = {}
self._emojis: Dict[int, Emoji] = {}
self._stickers: Dict[int, GuildSticker] = {}
self._guilds: Dict[int, Guild] = {}
# TODO: Why aren't the above and stuff below application_commands declared in __init__?
self._application_commands = set()
# Thought about making these two weakref.WeakValueDictionary's, but the bot could theoretically be holding on
# to them in a dev-defined, which would desync the bot from itself.
self._application_command_signatures = {}
self._application_command_ids = {}
if views:
self._view_store: ViewStore = ViewStore(self)
if modals:
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: Dict[int, VoiceProtocol] = {}
# LRU of max size 128
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: Dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)
else:
self._messages: Optional[Deque[Message]] = None
def process_chunk_requests(
self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool
) -> None:
removed = []
for key, request in self._chunk_requests.items():
if request.guild_id == guild_id and request.nonce == nonce:
request.add_members(members)
if complete:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
func = self.handlers[key]
except KeyError:
pass
else:
func(*args, **kwargs)
async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
coro = self.hooks[key]
except KeyError:
pass
else:
await coro(*args, **kwargs)
def self_id(self) -> Optional[int]:
u = self.user
return u.id if u else None
def intents(self) -> Intents:
ret = Intents.none()
ret.value = self._intents.value
return ret
def voice_clients(self) -> List[VoiceProtocol]:
return list(self._voice_clients.values())
def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:
# the keys of self._voice_clients are ints
return self._voice_clients.get(guild_id) # type: ignore
def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:
self._voice_clients[guild_id] = voice
def _remove_voice_client(self, guild_id: int) -> None:
self._voice_clients.pop(guild_id, None)
def _update_references(self, ws: DiscordWebSocket) -> None:
for vc in self.voice_clients:
vc.main_ws = ws # type: ignore
def store_user(self, data: UserPayload) -> User:
user_id = int(data["id"])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != "0000":
self._users[user_id] = user
user._stored = True
return user
def deref_user(self, user_id: int) -> None:
self._users.pop(user_id, None)
def create_user(self, data: Union[PartialUserPayload, UserPayload]) -> User:
return User(state=self, data=data)
def deref_user_no_intents(self, user_id: int) -> None:
return
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore
def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:
# the id will be present here
emoji_id = int(data["id"]) # type: ignore
self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)
return emoji
def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:
sticker_id = int(data["id"])
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
return sticker
def store_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.add_view(view, message_id)
def store_modal(self, modal: Modal, user_id: Optional[int] = None) -> None:
self._modal_store.add_modal(modal, user_id)
def remove_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.remove_view(view, message_id)
def remove_modal(self, modal: Modal) -> None:
self._modal_store.remove_modal(modal)
def prevent_view_updates_for(self, message_id: Optional[int]) -> Optional[View]:
return self._view_store.remove_message_tracking(message_id) # type: ignore
def all_views(self) -> List[View]:
return self._view_store.all_views()
def views(self, persistent: bool = True) -> List[View]:
return self._view_store.views(persistent)
def guilds(self) -> List[Guild]:
return list(self._guilds.values())
def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:
# the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore
def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild
def _remove_guild(self, guild: Guild) -> None:
self._guilds.pop(guild.id, None)
for emoji in guild.emojis:
self._emojis.pop(emoji.id, None)
for sticker in guild.stickers:
self._stickers.pop(sticker.id, None)
del guild
def emojis(self) -> List[Emoji]:
return list(self._emojis.values())
def stickers(self) -> List[GuildSticker]:
return list(self._stickers.values())
def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:
# the keys of self._emojis are ints
return self._emojis.get(emoji_id) # type: ignore
def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:
# the keys of self._stickers are ints
return self._stickers.get(sticker_id) # type: ignore
def private_channels(self) -> List[PrivateChannel]:
return list(self._private_channels.values())
def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:
try:
# the keys of self._private_channels are ints
value = self._private_channels[channel_id] # type: ignore
except KeyError:
return None
else:
self._private_channels.move_to_end(channel_id) # type: ignore
return value
def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:
# the keys of self._private_channels are ints
return self._private_channels_by_user.get(user_id) # type: ignore
def _add_private_channel(self, channel: PrivateChannel) -> None:
channel_id = channel.id
self._private_channels[channel_id] = channel
if len(self._private_channels) > 128:
_, to_remove = self._private_channels.popitem(last=False)
if isinstance(to_remove, DMChannel) and to_remove.recipient:
self._private_channels_by_user.pop(to_remove.recipient.id, None)
if isinstance(channel, DMChannel) and channel.recipient:
self._private_channels_by_user[channel.recipient.id] = channel
def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:
# self.user is *always* cached when this is called
channel = DMChannel(me=self.user, state=self, data=data) # type: ignore
self._add_private_channel(channel)
return channel
def _remove_private_channel(self, channel: PrivateChannel) -> None:
self._private_channels.pop(channel.id, None)
if isinstance(channel, DMChannel):
recipient = channel.recipient
if recipient is not None:
self._private_channels_by_user.pop(recipient.id, None)
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return (
utils.find(lambda m: m.id == msg_id, reversed(self._messages))
if self._messages
else None
)
def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self)
self._add_guild(guild)
return guild
def _guild_needs_chunking(self, guild: Guild) -> bool:
# If presences are enabled then we get back the old guild.large behaviour
return (
self._chunk_guilds
and not guild.chunked
and not (self._intents.presences and not guild.large)
)
def _get_guild_channel(
self, data: MessagePayload
) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
channel = self.get_channel(channel_id)
if channel is None:
channel = DMChannel._from_message(self, channel_id)
guild = getattr(channel, "guild", None)
else:
channel = guild and guild._resolve_channel(channel_id)
return channel or PartialMessageable(state=self, id=channel_id), guild
def application_commands(self) -> Set[BaseApplicationCommand]:
"""Gets a copy of the ApplicationCommand object set. If the original is given out and modified, massive desyncs
may occur. This should be used internally as well if size-changed-during-iteration is a worry.
"""
return self._application_commands.copy()
def get_application_command(self, command_id: int) -> Optional[BaseApplicationCommand]:
return self._application_command_ids.get(command_id, None)
def get_application_command_from_signature(
self,
*,
type: int,
qualified_name: str,
guild_id: Optional[int],
search_localizations: bool = False,
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
def get_parent_command(name: str, /) -> Optional[BaseApplicationCommand]:
found = self._application_command_signatures.get((name, type, guild_id))
if not search_localizations:
return found
for command in self._application_command_signatures.values():
if command.name_localizations and name in command.name_localizations.values():
found = command
break
return found
def find_children(
parent: Union[BaseApplicationCommand, SlashApplicationSubcommand], name: str, /
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
children: Dict[str, SlashApplicationSubcommand] = getattr(parent, "children", {})
if not children:
return parent
found = children.get(name)
if not search_localizations:
return found
subcommand: Union[BaseApplicationCommand, SlashApplicationSubcommand]
for subcommand in children.values():
if subcommand.name_localizations and name in subcommand.name_localizations.values():
found = subcommand
break
return found
parent: Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]] = None
if not qualified_name:
return None
if " " not in qualified_name:
return get_parent_command(qualified_name)
for command_name in qualified_name.split(" "):
if parent is None:
parent = get_parent_command(command_name)
else:
parent = find_children(parent, command_name)
return parent
def get_guild_application_commands(
self, guild_id: Optional[int] = None, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that have the given guild ID. If guild_id is None, all guild commands are returned. if
rollout is True, guild_ids_to_rollout is used.
"""
return [
app_cmd
for app_cmd in self.application_commands
if guild_id is None
or guild_id in app_cmd.guild_ids
or (rollout and guild_id in app_cmd.guild_ids_to_rollout)
]
def get_global_application_commands(
self, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that are registered globally. If rollout is True, is_global is used."""
return [
app_cmd
for app_cmd in self.application_commands
if (rollout and app_cmd.is_global) or None in app_cmd.command_ids
]
def add_application_command(
self,
command: BaseApplicationCommand,
*,
overwrite: bool = False,
use_rollout: bool = False,
pre_remove: bool = True,
) -> None:
"""Adds the command to the state and updates the state with any changes made to the command.
Removes all existing references, then adds them.
Safe to call multiple times on the same application command.
Parameters
----------
command: :class:`BaseApplicationCommand`
The command to add/update the state with.
overwrite: :class:`bool`
If the library will let you add a command that overlaps with an existing command. Default ``False``.
use_rollout: :class:`bool`
If the command should be added to the state with its rollout guild IDs.
pre_remove: :class:`bool`
If the command should be removed before adding it. This will clear all signatures from storage, including
rollout ones.
"""
if pre_remove:
self.remove_application_command(command)
signature_set = (
command.get_rollout_signatures() if use_rollout else command.get_signatures()
)
for signature in signature_set:
if not overwrite and (
found_command := self._application_command_signatures.get(signature, None)
):
if found_command is not command:
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate "
f"signatures."
)
# No else because we do not care if the command has its own signature already in.
else:
self._application_command_signatures[signature] = command
for command_id in command.command_ids.values():
# PyCharm flags found_command as it "might be referenced before assignment", but that can't happen due to it
# being in an AND statement.
# noinspection PyUnboundLocalVariable
if (
not overwrite
and (found_command := self._application_command_ids.get(command_id, None))
and found_command is not command
):
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate IDs."
)
self._application_command_ids[command_id] = command
# TODO: Add the command to guilds. Should it? Check if it does in the Guild add.
self._application_commands.add(command)
def remove_application_command(self, command: BaseApplicationCommand) -> None:
"""Removes the command and all signatures + associated IDs from the state.
Safe to call with commands that aren't in the state.
Parameters
----------
command: :class:`BaseApplicationCommand`
the command to remove from the state.
"""
signature_set = command.get_rollout_signatures()
for signature in signature_set:
self._application_command_signatures.pop(signature, None)
for cmd_id in command.command_ids.values():
self._application_command_ids.pop(cmd_id, None)
self._application_commands.discard(command)
def add_all_rollout_signatures(self) -> None:
"""This adds all command signatures for rollouts to the signature cache."""
for command in self._application_commands:
self.add_application_command(command, use_rollout=True)
async def sync_all_application_commands(
self,
data: Optional[Dict[Optional[int], List[ApplicationCommandPayload]]] = None,
*,
use_rollout: bool = True,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
ignore_forbidden: bool = True,
):
"""|coro|
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and
syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many
commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare
banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause
your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see :func:`Client.sync_application_commands`
Parameters
----------
data: Optional[Dict[Optional[:class:`int`], List[:class:`dict`]]]
Data to use when comparing local application commands to what Discord has. The key should be the
:class:`int` guild ID (`None` for global) corresponding to the value list of application command payloads
from Discord. Any guild ID's not provided will be fetched if needed. Defaults to ``None``
use_rollout: :class:`bool`
If the rollout guild IDs of commands should be used. Defaults to ``True``
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``
ignore_forbidden: :class:`bool`
If this command should raise an :class:`errors.Forbidden` exception when the bot encounters a guild where
it doesn't have permissions to view application commands.
Defaults to ``True``
"""
_log.debug("Beginning sync of all application commands.")
self._get_client().add_all_application_commands()
data = {} if data is None else data.copy()
if self.application_id is None:
raise TypeError("Could not get the current application's id")
for app_cmd in self.application_commands:
self.add_application_command(command=app_cmd, use_rollout=use_rollout)
if app_cmd.is_global and None not in data:
data[None] = await self.http.get_global_commands(self.application_id)
_log.debug("Fetched global application command data.")
if app_cmd.is_guild:
for guild_id in app_cmd.guild_ids_to_rollout if use_rollout else app_cmd.guild_ids:
if guild_id not in data:
try:
data[guild_id] = await self.http.get_guild_commands(
self.application_id, guild_id
)
_log.debug(
"Fetched guild application command data for guild ID %s", guild_id
)
except Forbidden as e:
if ignore_forbidden:
_log.warning(
"nextcord.Client: Forbidden error for %s, is the applications.commands "
"Oauth scope enabled? %s",
guild_id,
e,
)
else:
raise e
for guild_id in data:
_log.debug("Running sync for %s", "global" if guild_id is None else f"Guild {guild_id}")
await self.sync_application_commands(
data=data[guild_id],
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs
global commands if the guild_id is ``None``.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
_log.debug("Syncing commands to %s", guild_id)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
if not data:
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=data, guild_id=guild_id)
_log.debug("Command sync with Guild %s finished.", guild_id)
async def discover_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
"""|coro|
Associates existing, deletes unknown, and updates modified commands for either global commands or a specific
guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Parameters
----------
data: Optional[List[:class:`dict]]
Payload from ``HTTPClient.get_guild_commands`` or ``HTTPClient.get_global_commands`` to deploy with. If None,
the payload will be retrieved from Discord.
guild_id: Optional[:class:`int`]
Guild ID to deploy application commands to. If ``None``, global commands are deployed to.
associate_known: :class:`bool`
If True, commands on Discord that pass a signature check and a deep check will be associated with locally
added ApplicationCommand objects.
delete_unknown: :class:`bool`
If ``True``, commands on Discord that fail a signature check will be removed. If ``update_known`` is False,
commands that pass the signature check but fail the deep check will also be removed.
update_known: :class:`bool`
If ``True``, commands on Discord that pass a signature check but fail the deep check will be updated.
"""
if not associate_known and not delete_unknown and not update_known:
# If everything is disabled, there is no point in doing anything.
return
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
if not data:
if guild_id:
# we do not care about typeddict specificity here
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
for raw_response in data:
payload_type = raw_response["type"] if "type" in raw_response else 1
fixed_guild_id = raw_response.get("guild_id", None)
response_signature = {
"type": int(payload_type),
"qualified_name": raw_response["name"],
"guild_id": None if not fixed_guild_id else int(fixed_guild_id),
}
app_cmd = self.get_application_command_from_signature(**response_signature)
if app_cmd:
if not isinstance(app_cmd, BaseApplicationCommand):
raise ValueError(
(
f".get_application_command_from_signature with kwargs: {response_signature} "
f"returned {type(app_cmd)} but BaseApplicationCommand was expected."
)
)
if app_cmd.is_payload_valid(raw_response, guild_id):
if associate_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s associated with added command.",
response_signature,
)
app_cmd.parse_discord_response(self, raw_response)
self.add_application_command(app_cmd, use_rollout=True)
elif update_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, updating.",
response_signature,
)
await self.register_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
# TODO: Re-examine how worthwhile this is.
await self.delete_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, raw_response["id"]
)
else:
await self.http.delete_global_command(self.application_id, raw_response["id"])
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
warnings.warn(
".deploy_application_commands is deprecated, use .discover_application_commands instead.",
stacklevel=2,
category=FutureWarning,
)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".associate_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=True,
delete_unknown=False,
update_known=False,
)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".delete_unknown_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=True,
update_known=False,
)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".update_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=False,
update_known=True,
)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers locally added application commands that don't match a signature that Discord has registered for
either global commands or a specific guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
"""
if not data:
if self.application_id is None:
raise TypeError("Could not get the current application id")
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
data_signatures = [
(
raw_response["name"],
int(raw_response["type"] if "type" in raw_response else 1),
int(temp) if (temp := raw_response.get("guild_id", None)) else temp,
)
for raw_response in data
]
# add_application_command can change the size of the dictionary, and apparently .items() doesn't prevent that
# "RuntimeError: dictionary changed size during iteration" from happening. So a copy is made for just this.
for signature, app_cmd in self._application_command_signatures.copy().items():
if (
signature not in data_signatures and signature[2] == guild_id
): # index 2 of the tuple is the guild ID.
await self.register_application_command(app_cmd, guild_id)
async def register_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers the given application command either for a specific guild or globally and adds the command to the bot.
Parameters
----------
command: :class:`BaseApplicationCommand`
Application command to register.
guild_id: Optional[:class:`int`]
ID of the guild to register the application commands to. If set to ``None``, the commands will be registered
as global commands instead. Defaults to ``None``.
"""
payload: EditApplicationCommand = command.get_payload(guild_id) # type: ignore
_log.info(
"nextcord.ConnectionState: Registering command with signature %s",
command.get_signature(guild_id),
)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
try:
if guild_id:
raw_response = await self.http.upsert_guild_command(
self.application_id, guild_id, payload
)
else:
raw_response = await self.http.upsert_global_command(self.application_id, payload)
except Exception as e:
_log.error("Error registering command %s: %s", command.error_name, e)
raise e
command.parse_discord_response(self, raw_response)
self.add_application_command(command, pre_remove=False)
async def delete_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Deletes the given application from Discord for the given guild ID or globally, then removes the signature and
command ID from the cache if possible.
Parameters
----------
command: :class:`ApplicationCommand`
Application command to delete.
guild_id: Optional[:class:`int`]
Guild ID to delete the application commands from. If ``None``, the command is deleted from global.
"""
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
try:
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, command.command_ids[guild_id]
)
else:
await self.http.delete_global_command(
self.application_id, command.command_ids[guild_id]
)
self._application_command_ids.pop(command.command_ids[guild_id], None)
self._application_command_signatures.pop(command.get_signature(guild_id), None)
except KeyError as e:
if guild_id:
_log.error(
"Could not globally unregister command %s "
"as it is not registered in the provided guild.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, "
"as it is not registered in the provided guild."
) from e
_log.error(
"Could not globally unregister command %s as it is not a global command.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, as it is not a global command."
) from e
except Exception as e:
_log.error("Error unregistering command %s: %s", command.error_name, e)
raise e
# async def register_bulk_application_commands(self) -> None:
# # TODO: Using Bulk upsert seems to delete all commands
# # It might be good to keep this around as a reminder for future work. Bulk upsert seem to delete everything
# # that isn't part of that bulk upsert, for both global and guild commands. While useful, this will
# # update/overwrite existing commands, which may (needs testing) wipe out all permissions associated with those
# # commands. Look for an opportunity to use bulk upsert.
# raise NotImplementedError
async def chunker(
self,
guild_id: int,
query: str = "",
limit: int = 0,
presences: bool = False,
*,
nonce: Optional[str] = None,
) -> None:
ws = self._get_websocket(guild_id) # This is ignored upstream
await ws.request_chunks(
guild_id, query=query, limit=limit, presences=presences, nonce=nonce
)
async def query_members(
self,
guild: Guild,
query: Optional[str],
limit: int,
user_ids: Optional[List[int]],
cache: bool,
presences: bool,
) -> List[Member]:
guild_id = guild.id
ws = self._get_websocket(guild_id)
if ws is None: # pyright: ignore[reportUnnecessaryComparison]
raise RuntimeError("Somehow do not have a websocket for this guild_id")
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request
try:
# start the query operation
await ws.request_chunks(
guild_id,
query=query,
limit=limit,
user_ids=user_ids,
presences=presences,
nonce=request.nonce,
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
_log.warning(
"Timed out waiting for chunks with query %r and limit %d for guild_id %d",
query,
limit,
guild_id,
)
raise
async def _delay_ready(self) -> None:
try:
states = []
while True:
# this snippet of code is basically waiting N seconds
# until the last GUILD_CREATE was sent
try:
guild = await asyncio.wait_for(
self._ready_state.get(), timeout=self.guild_ready_timeout
)
except asyncio.TimeoutError:
break
else:
if self._guild_needs_chunking(guild):
future = await self.chunk_guild(guild, wait=False)
states.append((guild, future))
elif guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
for guild, future in states:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
_log.warning(
"Shard ID %s timed out waiting for chunks for guild_id %s.",
guild.shard_id,
guild.id,
)
if guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
# remove the state
# AttributeError: already been deleted somehow
with contextlib.suppress(AttributeError):
del self._ready_state
except asyncio.CancelledError:
pass
else:
# dispatch the event
self.call_handlers("ready")
self.dispatch("ready")
finally:
self._ready_task = None
def parse_ready(self, data) -> None:
if self._ready_task is not None:
self._ready_task.cancel()
self._ready_state = asyncio.Queue()
self.clear(views=False)
self.user = ClientUser(state=self, data=data["user"])
self.store_user(data["user"])
if self.application_id is None:
try:
application = data["application"]
except KeyError:
pass
else:
self.application_id = utils.get_as_snowflake(application, "id")
# flags will always be present here
self.application_flags = ApplicationFlags._from_value(application["flags"])
for guild_data in data["guilds"]:
self._add_guild_from_data(guild_data)
self.dispatch("connect")
self._ready_task = asyncio.create_task(self._delay_ready())
def parse_resumed(self, data) -> None:
self.dispatch("resumed")
def parse_message_create(self, data) -> None:
channel, _ = self._get_guild_channel(data)
# channel would be the correct type here
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch("message", message)
if self._messages is not None:
self._messages.append(message)
# we ensure that the channel is either a TextChannel, ForumChannel, Thread or VoiceChannel
if channel and channel.__class__ in (TextChannel, ForumChannel, Thread, VoiceChannel):
channel.last_message_id = message.id # type: ignore
def parse_message_delete(self, data) -> None:
raw = RawMessageDeleteEvent(data)
found = self._get_message(raw.message_id)
raw.cached_message = found
self.dispatch("raw_message_delete", raw)
if self._messages is not None and found is not None:
self.dispatch("message_delete", found)
self._messages.remove(found)
def parse_message_delete_bulk(self, data) -> None:
raw = RawBulkMessageDeleteEvent(data)
if self._messages:
found_messages = [
message for message in self._messages if message.id in raw.message_ids
]
else:
found_messages = []
raw.cached_messages = found_messages
self.dispatch("raw_bulk_message_delete", raw)
if found_messages:
self.dispatch("bulk_message_delete", found_messages)
for msg in found_messages:
# self._messages won't be None here
self._messages.remove(msg) # type: ignore
def parse_message_update(self, data) -> None:
raw = RawMessageUpdateEvent(data)
message = self._get_message(raw.message_id)
if message is not None:
older_message = copy.copy(message)
raw.cached_message = older_message
self.dispatch("raw_message_edit", raw)
message._update(data)
# Coerce the `after` parameter to take the new updated Member
# ref: #5999
older_message.author = message.author
self.dispatch("message_edit", older_message, message)
else:
self.dispatch("raw_message_edit", raw)
if "components" in data and self._view_store.is_message_tracked(raw.message_id):
self._view_store.update_from_message(raw.message_id, data["components"])
def parse_message_reaction_add(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(
self, id=emoji_id, animated=emoji.get("animated", False), name=emoji["name"]
)
raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_reaction_add", raw)
# rich interface here
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
reaction = message._add_reaction(data, emoji, raw.user_id)
user = raw.member or self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_add", reaction, user)
def parse_message_reaction_remove_all(self, data) -> None:
raw = RawReactionClearEvent(data)
self.dispatch("raw_reaction_clear", raw)
message = self._get_message(raw.message_id)
if message is not None:
old_reactions = message.reactions.copy()
message.reactions.clear()
self.dispatch("reaction_clear", message, old_reactions)
def parse_message_reaction_remove(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionActionEvent(data, emoji, "REACTION_REMOVE")
self.dispatch("raw_reaction_remove", raw)
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
try:
reaction = message._remove_reaction(data, emoji, raw.user_id)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
user = self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_remove", reaction, user)
def parse_message_reaction_remove_emoji(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionClearEmojiEvent(data, emoji)
self.dispatch("raw_reaction_clear_emoji", raw)
message = self._get_message(raw.message_id)
if message is not None:
try:
reaction = message._clear_emoji(emoji)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
if reaction:
self.dispatch("reaction_clear_emoji", reaction)
def parse_interaction_create(self, data) -> None:
interaction = self._get_client().get_interaction(data=data)
if data["type"] == 3: # interaction component
custom_id = interaction.data["custom_id"] # type: ignore
component_type = interaction.data["component_type"] # type: ignore
self._view_store.dispatch(component_type, custom_id, interaction)
if data["type"] == 5: # modal submit
custom_id = interaction.data["custom_id"] # type: ignore
# key exists if type is 5 etc
self._modal_store.dispatch(custom_id, interaction)
self.dispatch("interaction", interaction)
def parse_presence_update(self, data) -> None:
guild_id = utils.get_as_snowflake(data, "guild_id")
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
user = data["user"]
member_id = int(user["id"])
member = guild.get_member(member_id)
if member is None:
_log.debug(
"PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding", member_id
)
return
old_member = Member._copy(member)
user_update = member._presence_update(data=data, user=user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("presence_update", old_member, member)
def parse_user_update(self, data) -> None:
# self.user is *always* cached when this is called
user: ClientUser = self.user # type: ignore
user._update(data)
ref = self._users.get(user.id)
if ref:
ref._update(data)
def parse_invite_create(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_create", invite)
def parse_invite_delete(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_delete", invite)
def parse_channel_delete(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = int(data["id"])
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
guild._remove_channel(channel)
self.dispatch("guild_channel_delete", channel)
def parse_channel_update(self, data) -> None:
channel_type = try_enum(ChannelType, data.get("type"))
channel_id = int(data["id"])
if channel_type is ChannelType.group:
channel = self._get_private_channel(channel_id)
old_channel = copy.copy(channel)
# the channel is a GroupChannel
channel._update_group(data) # type: ignore
self.dispatch("private_channel_update", old_channel, channel)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
old_channel = copy.copy(channel)
channel._update(guild, data)
self.dispatch("guild_channel_update", old_channel, channel)
else:
_log.debug(
"CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
else:
_log.debug("CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
def parse_channel_create(self, data) -> None:
factory, _ = _channel_factory(data["type"])
if factory is None:
_log.debug(
"CHANNEL_CREATE referencing an unknown channel type %s. Discarding.", data["type"]
)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
# the factory can't be a DMChannel or GroupChannel here
channel = factory(guild=guild, state=self, data=data) # type: ignore
guild._add_channel(channel) # type: ignore
self.dispatch("guild_channel_create", channel)
else:
_log.debug("CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
def parse_channel_pins_update(self, data) -> None:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
guild = None
channel = self._get_private_channel(channel_id)
else:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
_log.debug(
"CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
return
last_pin = (
utils.parse_time(data["last_pin_timestamp"]) if data["last_pin_timestamp"] else None
)
if guild is None:
self.dispatch("private_channel_pins_update", channel, last_pin)
else:
self.dispatch("guild_channel_pins_update", channel, last_pin)
def parse_thread_create(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_CREATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
has_thread = guild.get_thread(thread.id)
guild._add_thread(thread)
if not has_thread:
# `newly_created` is documented outside of a thread's fields:
# https://discord.dev/topics/gateway-events#thread-create
if data.get("newly_created", False):
if isinstance(thread.parent, ForumChannel):
thread.parent.last_message_id = thread.id
self.dispatch("thread_create", thread)
# Avoid an unnecessary breaking change right now by dispatching `thread_join` for
# threads that were already created.
self.dispatch("thread_join", thread)
def parse_thread_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
old = copy.copy(thread)
thread._update(data)
self.dispatch("thread_update", old, thread)
else:
thread = Thread(guild=guild, state=guild._state, data=data)
guild._add_thread(thread)
self.dispatch("thread_join", thread)
def parse_thread_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_DELETE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
guild._remove_thread(thread)
self.dispatch("thread_delete", thread)
def parse_thread_list_sync(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding", guild_id)
return
try:
channel_ids = set(data["channel_ids"])
except KeyError:
# If not provided, then the entire guild is being synced
# So all previous thread data should be overwritten
previous_threads = guild._threads.copy()
guild._clear_threads()
else:
previous_threads = guild._filter_threads(channel_ids)
threads = {d["id"]: guild._store_thread(d) for d in data.get("threads", [])}
for member in data.get("members", []):
try:
# note: member['id'] is the thread_id
thread = threads[member["id"]]
except KeyError:
continue
else:
thread._add_member(ThreadMember(thread, member))
for thread in threads.values():
old = previous_threads.pop(thread.id, None)
if old is None:
self.dispatch("thread_join", thread)
for thread in previous_threads.values():
self.dispatch("thread_remove", thread)
def parse_thread_member_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
member = ThreadMember(thread, data)
thread.me = member
def parse_thread_members_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
added_members = [ThreadMember(thread, d) for d in data.get("added_members", [])]
removed_member_ids = [int(x) for x in data.get("removed_member_ids", [])]
self_id = self.self_id
for member in added_members:
if member.id != self_id:
thread._add_member(member)
self.dispatch("thread_member_join", member)
else:
thread.me = member
self.dispatch("thread_join", thread)
for member_id in removed_member_ids:
if member_id != self_id:
member = thread._pop_member(member_id)
if member is not None:
self.dispatch("thread_member_remove", member)
else:
self.dispatch("thread_remove", thread)
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = Member(guild=guild, data=data, state=self)
if self.member_cache_flags.joined:
guild._add_member(member)
with contextlib.suppress(AttributeError):
guild._member_count += 1
self.dispatch("member_join", member)
def parse_guild_member_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
with contextlib.suppress(AttributeError):
guild._member_count -= 1
user_id = int(data["user"]["id"])
member = guild.get_member(user_id)
if member is not None:
guild._remove_member(member)
self.dispatch("member_remove", member)
else:
_log.debug(
(
"GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s."
"Falling back to raw data."
),
data["guild_id"],
)
raw = RawMemberRemoveEvent(data=data, state=self)
self.dispatch("raw_member_remove", raw)
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user = data["user"]
user_id = int(user["id"])
if guild is None:
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = guild.get_member(user_id)
if member is not None:
old_member = Member._copy(member)
member._update(data)
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("member_update", old_member, member)
else:
if self.member_cache_flags.joined:
member = Member(data=data, guild=guild, state=self)
# Force an update on the inner user if necessary
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
guild._add_member(member)
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.", user_id
)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_emojis = guild.emojis
for emoji in before_emojis:
self._emojis.pop(emoji.id, None)
guild.emojis = tuple([self.store_emoji(guild, d) for d in data["emojis"]])
self.dispatch("guild_emojis_update", guild, before_emojis, guild.emojis)
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_stickers = guild.stickers
for emoji in before_stickers:
self._stickers.pop(emoji.id, None)
guild.stickers = tuple([self.store_sticker(guild, d) for d in data["stickers"]])
self.dispatch("guild_stickers_update", guild, before_stickers, guild.stickers)
def _get_create_guild(self, data):
if data.get("unavailable") is False:
# GUILD_CREATE with unavailable in the response
# usually means that the guild has become available
# and is therefore in the cache
guild = self._get_guild(int(data["id"]))
if guild is not None:
guild.unavailable = False
guild._from_data(data)
return guild
return self._add_guild_from_data(data)
def is_guild_evicted(self, guild) -> bool:
return guild.id not in self._guilds
async def chunk_guild(self, guild, *, wait: bool = True, cache=None):
if cache is None:
cache = self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id)
if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce)
if wait:
return await request.wait()
return request.get_future()
async def _chunk_and_dispatch(self, guild, unavailable) -> None:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
_log.info("Somehow timed out waiting for chunks.")
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_create(self, data) -> None:
unavailable = data.get("unavailable")
if unavailable is True:
# joined a guild with unavailable == True so..
return
guild = self._get_create_guild(data)
try:
# Notify the on_ready state, if any, that this guild is complete.
self._ready_state.put_nowait(guild)
except AttributeError:
pass
else:
# If we're waiting for the event, put the rest on hold
return
# check if it requires chunking
if self._guild_needs_chunking(guild):
task = asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))
self._chunk_tasks[guild.id] = task
task.add_done_callback(lambda _t: self._chunk_tasks.pop(guild.id, None))
return
# Dispatch available if newly available
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_update(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is not None:
old_guild = copy.copy(guild)
guild._from_data(data)
self.dispatch("guild_update", old_guild, guild)
else:
_log.debug("GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.", data["id"])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is None:
_log.debug("GUILD_DELETE referencing an unknown guild ID: %s. Discarding.", data["id"])
return
if data.get("unavailable", False):
# GUILD_DELETE with unavailable being True means that the
# guild that was available is now currently unavailable
guild.unavailable = True
self.dispatch("guild_unavailable", guild)
return
# do a cleanup of the messages cache
if self._messages is not None:
self._messages: Optional[Deque[Message]] = deque(
(msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages
)
self._remove_guild(guild)
self.dispatch("guild_remove", guild)
def parse_guild_ban_add(self, data) -> None:
# we make the assumption that GUILD_BAN_ADD is done
# before GUILD_MEMBER_REMOVE is called
# hence we don't remove it from cache or do anything
# strange with it, the main purpose of this event
# is mainly to dispatch to another event worth listening to for logging
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
user = User(data=data["user"], state=self)
except KeyError:
pass
else:
member = guild.get_member(user.id) or user
self.dispatch("member_ban", guild, member)
def parse_guild_ban_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None and "user" in data:
user = self.store_user(data["user"])
self.dispatch("member_unban", guild, user)
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
role_data = data["role"]
role = Role(guild=guild, data=role_data, state=self)
guild._add_role(role)
self.dispatch("guild_role_create", role)
def parse_guild_role_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_id = int(data["role_id"])
try:
role = guild._remove_role(role_id)
except KeyError:
return
else:
self.dispatch("guild_role_delete", role)
else:
_log.debug(
"GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_data = data["role"]
role_id = int(role_data["id"])
role = guild.get_role(role_id)
if role is not None:
old_role = copy.copy(role)
role._update(role_data)
self.dispatch("guild_role_update", old_role, role)
else:
_log.debug(
"GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
presences = data.get("presences", [])
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get("members", [])] # type: ignore
_log.debug("Processed a chunk for %s members in guild ID %s.", len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
for presence in presences:
user = presence["user"]
member_id = user["id"]
member = member_dict.get(member_id)
if member is not None:
member._presence_update(presence, user)
complete = data.get("chunk_index", 0) + 1 == data.get("chunk_count")
self.process_chunk_requests(guild_id, data.get("nonce"), members, complete)
def parse_guild_integrations_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
self.dispatch("guild_integrations_update", guild)
else:
_log.debug(
"GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_create", integration)
else:
_log.debug(
"INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_update", integration)
else:
_log.debug(
"INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is not None:
raw = RawIntegrationDeleteEvent(data)
self.dispatch("raw_integration_delete", raw)
else:
_log.debug(
"INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding", data["guild_id"]
)
return
channel = guild.get_channel(int(data["channel_id"]))
if channel is not None:
self.dispatch("webhooks_update", channel)
else:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.",
data["channel_id"],
)
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = StageInstance(guild=guild, state=self, data=data)
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch("stage_instance_create", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = guild._stage_instances.get(int(data["id"]))
if stage_instance is not None:
old_stage_instance = copy.copy(stage_instance)
stage_instance._update(data)
self.dispatch("stage_instance_update", old_stage_instance, stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
stage_instance = guild._stage_instances.pop(int(data["id"]))
except KeyError:
pass
else:
self.dispatch("stage_instance_delete", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = utils.get_as_snowflake(data, "channel_id")
flags = self.member_cache_flags
# self.user is *always* cached when this is called
self_id = self.user.id # type: ignore
if guild is not None:
if int(data["user_id"]) == self_id:
voice = self._get_voice_client(guild.id)
if voice is not None:
coro = voice.on_voice_state_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice state update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
member, before, after = guild._update_voice_state(data, channel_id) # type: ignore
after = copy.copy(after)
if member is not None:
if flags.voice:
if channel_id is None and flags._voice_only and member.id != self_id:
# Only remove from cache if we only have the voice flag enabled
# Member doesn't meet the Snowflake protocol currently
guild._remove_member(member)
elif channel_id is not None:
guild._add_member(member)
self.dispatch("voice_state_update", member, before, after)
else:
_log.debug(
"VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.",
data["user_id"],
)
def parse_voice_server_update(self, data) -> None:
try:
key_id = int(data["guild_id"])
except KeyError:
key_id = int(data["channel_id"])
vc = self._get_voice_client(key_id)
if vc is not None:
coro = vc.on_voice_server_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice server update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
def parse_typing_start(self, data) -> None:
raw = RawTypingEvent(data)
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_typing", raw)
channel, guild = self._get_guild_channel(data)
if channel is not None: # pyright: ignore[reportUnnecessaryComparison]
user = raw.member or self._get_typing_user(channel, raw.user_id) # type: ignore
# will be messageable channel if we get here
if user is not None:
self.dispatch("typing", channel, user, raw.when)
def _get_typing_user(
self, channel: Optional[MessageableChannel], user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, DMChannel):
return channel.recipient or self.get_user(user_id)
if isinstance(channel, (Thread, TextChannel)):
return channel.guild.get_member(user_id)
if isinstance(channel, GroupChannel):
return utils.find(lambda x: x.id == user_id, channel.recipients)
return self.get_user(user_id)
def _get_reaction_user(
self, channel: MessageableChannel, user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, TextChannel):
return channel.guild.get_member(user_id)
return self.get_user(user_id)
def get_reaction_emoji(self, data) -> Union[Emoji, PartialEmoji]:
emoji_id = utils.get_as_snowflake(data, "id")
if not emoji_id:
return data["name"]
try:
return self._emojis[emoji_id]
except KeyError:
return PartialEmoji.with_state(
self, animated=data.get("animated", False), id=emoji_id, name=data["name"]
)
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:
emoji_id = emoji.id
if not emoji_id:
return emoji.name
try:
return self._emojis[emoji_id]
except KeyError:
return emoji
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel
return None
def get_scheduled_event(self, id: int) -> Optional[ScheduledEvent]:
for guild in self.guilds:
if event := guild.get_scheduled_event(id):
return event
return None
def create_message(
self,
*,
channel: MessageableChannel,
data: MessagePayload,
) -> Message:
return Message(state=self, channel=channel, data=data)
def create_scheduled_event(
self, *, guild: Guild, data: ScheduledEventPayload
) -> ScheduledEvent:
return ScheduledEvent(state=self, guild=guild, data=data)
def parse_guild_scheduled_event_create(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
event = self.create_scheduled_event(guild=guild, data=data)
guild._add_scheduled_event(event)
self.dispatch("guild_scheduled_event_create", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_update(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
old = copy.copy(event)
event._update(data)
self.dispatch("guild_scheduled_event_update", old, event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_delete(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
guild._remove_scheduled_event(event.id)
self.dispatch("guild_scheduled_event_delete", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_add(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
u = ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
)
event._add_user(u)
self.dispatch("guild_scheduled_event_user_add", event, u)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_remove(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
event._remove_user(int(data["user_id"]))
self.dispatch(
"guild_scheduled_event_user_remove",
event,
ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
),
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_auto_moderation_rule_create(self, data) -> None:
self.dispatch(
"auto_moderation_rule_create",
AutoModerationRule(data=data, state=self),
)
def parse_auto_moderation_rule_update(self, data) -> None:
self.dispatch("auto_moderation_rule_update", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_rule_delete(self, data) -> None:
self.dispatch("auto_moderation_rule_delete", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_action_execution(self, data) -> None:
self.dispatch(
"auto_moderation_action_execution", AutoModerationActionExecution(data=data, state=self)
)
def parse_guild_audit_log_entry_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user_id = None if data.get("user_id") is None else int(data["user_id"])
user = self.get_user(user_id)
users = {} if user_id is None or user is None else {user_id: user}
if guild is not None:
entry = AuditLogEntry(auto_moderation_rules={}, users=users, data=data, guild=guild)
self.dispatch("guild_audit_log_entry_create", entry)
else:
_log.debug(
"guild_audit_log_entry_create wasn't dispatched because the guild (%r) and/or user (%r) are None!",
guild,
user,
)
def create_activity(state: ConnectionState, data: ActivityPayload) -> ActivityTypes:
... | null |
160,934 | from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, overload
from .asset import Asset
from .colour import Colour
from .enums import ActivityType, try_enum
from .partial_emoji import PartialEmoji
from .utils import get_as_snowflake
class ConnectionState:
if TYPE_CHECKING:
_get_websocket: Callable[..., DiscordWebSocket]
_get_client: Callable[..., Client]
_parsers: Dict[str, Callable[[Dict[str, Any]], None]]
def __init__(
self,
*,
dispatch: Callable,
handlers: Dict[str, Callable],
hooks: Dict[str, Callable],
http: HTTPClient,
loop: asyncio.AbstractEventLoop,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Status] = None,
intents: Intents = Intents.default(),
chunk_guilds_at_startup: bool = MISSING,
member_cache_flags: MemberCacheFlags = MISSING,
) -> None:
self.loop: asyncio.AbstractEventLoop = loop
self.http: HTTPClient = http
self.max_messages: Optional[int] = max_messages
if self.max_messages is not None and self.max_messages <= 0:
self.max_messages = 1000
self.dispatch: Callable = dispatch
self.handlers: Dict[str, Callable] = handlers
self.hooks: Dict[str, Callable] = hooks
self.shard_count: Optional[int] = None
self._ready_task: Optional[asyncio.Task] = None
self.application_id: Optional[int] = application_id
self.heartbeat_timeout: float = heartbeat_timeout
self.guild_ready_timeout: float = guild_ready_timeout
if self.guild_ready_timeout < 0:
raise ValueError("guild_ready_timeout cannot be negative")
if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):
raise TypeError("allowed_mentions parameter must be AllowedMentions")
self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions
self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}
self._chunk_tasks: Dict[Union[int, str], asyncio.Task[None]] = {}
self._background_tasks: Set[asyncio.Task] = set()
if activity is not None:
if not isinstance(activity, BaseActivity):
raise TypeError("activity parameter must derive from BaseActivity.")
raw_activity = activity.to_dict()
else:
raw_activity = activity
raw_status = ("invisible" if status is Status.offline else str(status)) if status else None
if not isinstance(intents, Intents):
raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
if not intents.guilds:
_log.warning("Guilds intent seems to be disabled. This may cause state related issues.")
if chunk_guilds_at_startup is MISSING:
chunk_guilds_at_startup = intents.members
self._chunk_guilds: bool = chunk_guilds_at_startup
# Ensure these two are set properly
if not intents.members and self._chunk_guilds:
raise ValueError("Intents.members must be enabled to chunk guilds at startup.")
if member_cache_flags is MISSING:
member_cache_flags = MemberCacheFlags.from_intents(intents)
else:
if not isinstance(member_cache_flags, MemberCacheFlags):
raise TypeError(
"member_cache_flags parameter must be MemberCacheFlags "
f"not {type(member_cache_flags)!r}"
)
member_cache_flags._verify_intents(intents)
self.member_cache_flags: MemberCacheFlags = member_cache_flags
self._activity: Optional[ActivityPayload] = raw_activity
self._status: Optional[str] = raw_status
self._intents: Intents = intents
# A set of all application command objects available. Set because duplicates should not exist.
self._application_commands: Set[BaseApplicationCommand] = set()
# A dictionary of all available unique command signatures. Compiled at runtime because needing to iterate
# through all application commands would take far more time. If memory is problematic, perhaps this can go?
self._application_command_signatures: Dict[
Tuple[Optional[str], int, Optional[int]], BaseApplicationCommand
] = {}
# A dictionary of Discord Application Command ID's and the ApplicationCommand object they correspond to.
self._application_command_ids: Dict[int, BaseApplicationCommand] = {}
if not intents.members or member_cache_flags._empty:
self.store_user = self.create_user
self.deref_user = self.deref_user_no_intents
self.parsers = parsers = {}
for attr, func in inspect.getmembers(self):
if attr.startswith("parse_"):
parsers[attr[6:].upper()] = func
self.clear()
def clear(self, *, views: bool = True, modals: bool = True) -> None:
self.user: Optional[ClientUser] = None
# Originally, this code used WeakValueDictionary to maintain references to the
# global user mapping.
# However, profiling showed that this came with two cons:
# 1. The __weakref__ slot caused a non-trivial increase in memory
# 2. The performance of the mapping caused store_user to be a bottleneck.
# Since this is undesirable, a mapping is now used instead with stored
# references now using a regular dictionary with eviction being done
# using __del__. Testing this for memory leaks led to no discernible leaks,
# though more testing will have to be done.
self._users: Dict[int, User] = {}
self._emojis: Dict[int, Emoji] = {}
self._stickers: Dict[int, GuildSticker] = {}
self._guilds: Dict[int, Guild] = {}
# TODO: Why aren't the above and stuff below application_commands declared in __init__?
self._application_commands = set()
# Thought about making these two weakref.WeakValueDictionary's, but the bot could theoretically be holding on
# to them in a dev-defined, which would desync the bot from itself.
self._application_command_signatures = {}
self._application_command_ids = {}
if views:
self._view_store: ViewStore = ViewStore(self)
if modals:
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: Dict[int, VoiceProtocol] = {}
# LRU of max size 128
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: Dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)
else:
self._messages: Optional[Deque[Message]] = None
def process_chunk_requests(
self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool
) -> None:
removed = []
for key, request in self._chunk_requests.items():
if request.guild_id == guild_id and request.nonce == nonce:
request.add_members(members)
if complete:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
func = self.handlers[key]
except KeyError:
pass
else:
func(*args, **kwargs)
async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
coro = self.hooks[key]
except KeyError:
pass
else:
await coro(*args, **kwargs)
def self_id(self) -> Optional[int]:
u = self.user
return u.id if u else None
def intents(self) -> Intents:
ret = Intents.none()
ret.value = self._intents.value
return ret
def voice_clients(self) -> List[VoiceProtocol]:
return list(self._voice_clients.values())
def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:
# the keys of self._voice_clients are ints
return self._voice_clients.get(guild_id) # type: ignore
def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:
self._voice_clients[guild_id] = voice
def _remove_voice_client(self, guild_id: int) -> None:
self._voice_clients.pop(guild_id, None)
def _update_references(self, ws: DiscordWebSocket) -> None:
for vc in self.voice_clients:
vc.main_ws = ws # type: ignore
def store_user(self, data: UserPayload) -> User:
user_id = int(data["id"])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != "0000":
self._users[user_id] = user
user._stored = True
return user
def deref_user(self, user_id: int) -> None:
self._users.pop(user_id, None)
def create_user(self, data: Union[PartialUserPayload, UserPayload]) -> User:
return User(state=self, data=data)
def deref_user_no_intents(self, user_id: int) -> None:
return
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore
def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:
# the id will be present here
emoji_id = int(data["id"]) # type: ignore
self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)
return emoji
def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:
sticker_id = int(data["id"])
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
return sticker
def store_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.add_view(view, message_id)
def store_modal(self, modal: Modal, user_id: Optional[int] = None) -> None:
self._modal_store.add_modal(modal, user_id)
def remove_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.remove_view(view, message_id)
def remove_modal(self, modal: Modal) -> None:
self._modal_store.remove_modal(modal)
def prevent_view_updates_for(self, message_id: Optional[int]) -> Optional[View]:
return self._view_store.remove_message_tracking(message_id) # type: ignore
def all_views(self) -> List[View]:
return self._view_store.all_views()
def views(self, persistent: bool = True) -> List[View]:
return self._view_store.views(persistent)
def guilds(self) -> List[Guild]:
return list(self._guilds.values())
def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:
# the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore
def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild
def _remove_guild(self, guild: Guild) -> None:
self._guilds.pop(guild.id, None)
for emoji in guild.emojis:
self._emojis.pop(emoji.id, None)
for sticker in guild.stickers:
self._stickers.pop(sticker.id, None)
del guild
def emojis(self) -> List[Emoji]:
return list(self._emojis.values())
def stickers(self) -> List[GuildSticker]:
return list(self._stickers.values())
def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:
# the keys of self._emojis are ints
return self._emojis.get(emoji_id) # type: ignore
def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:
# the keys of self._stickers are ints
return self._stickers.get(sticker_id) # type: ignore
def private_channels(self) -> List[PrivateChannel]:
return list(self._private_channels.values())
def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:
try:
# the keys of self._private_channels are ints
value = self._private_channels[channel_id] # type: ignore
except KeyError:
return None
else:
self._private_channels.move_to_end(channel_id) # type: ignore
return value
def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:
# the keys of self._private_channels are ints
return self._private_channels_by_user.get(user_id) # type: ignore
def _add_private_channel(self, channel: PrivateChannel) -> None:
channel_id = channel.id
self._private_channels[channel_id] = channel
if len(self._private_channels) > 128:
_, to_remove = self._private_channels.popitem(last=False)
if isinstance(to_remove, DMChannel) and to_remove.recipient:
self._private_channels_by_user.pop(to_remove.recipient.id, None)
if isinstance(channel, DMChannel) and channel.recipient:
self._private_channels_by_user[channel.recipient.id] = channel
def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:
# self.user is *always* cached when this is called
channel = DMChannel(me=self.user, state=self, data=data) # type: ignore
self._add_private_channel(channel)
return channel
def _remove_private_channel(self, channel: PrivateChannel) -> None:
self._private_channels.pop(channel.id, None)
if isinstance(channel, DMChannel):
recipient = channel.recipient
if recipient is not None:
self._private_channels_by_user.pop(recipient.id, None)
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return (
utils.find(lambda m: m.id == msg_id, reversed(self._messages))
if self._messages
else None
)
def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self)
self._add_guild(guild)
return guild
def _guild_needs_chunking(self, guild: Guild) -> bool:
# If presences are enabled then we get back the old guild.large behaviour
return (
self._chunk_guilds
and not guild.chunked
and not (self._intents.presences and not guild.large)
)
def _get_guild_channel(
self, data: MessagePayload
) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
channel = self.get_channel(channel_id)
if channel is None:
channel = DMChannel._from_message(self, channel_id)
guild = getattr(channel, "guild", None)
else:
channel = guild and guild._resolve_channel(channel_id)
return channel or PartialMessageable(state=self, id=channel_id), guild
def application_commands(self) -> Set[BaseApplicationCommand]:
"""Gets a copy of the ApplicationCommand object set. If the original is given out and modified, massive desyncs
may occur. This should be used internally as well if size-changed-during-iteration is a worry.
"""
return self._application_commands.copy()
def get_application_command(self, command_id: int) -> Optional[BaseApplicationCommand]:
return self._application_command_ids.get(command_id, None)
def get_application_command_from_signature(
self,
*,
type: int,
qualified_name: str,
guild_id: Optional[int],
search_localizations: bool = False,
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
def get_parent_command(name: str, /) -> Optional[BaseApplicationCommand]:
found = self._application_command_signatures.get((name, type, guild_id))
if not search_localizations:
return found
for command in self._application_command_signatures.values():
if command.name_localizations and name in command.name_localizations.values():
found = command
break
return found
def find_children(
parent: Union[BaseApplicationCommand, SlashApplicationSubcommand], name: str, /
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
children: Dict[str, SlashApplicationSubcommand] = getattr(parent, "children", {})
if not children:
return parent
found = children.get(name)
if not search_localizations:
return found
subcommand: Union[BaseApplicationCommand, SlashApplicationSubcommand]
for subcommand in children.values():
if subcommand.name_localizations and name in subcommand.name_localizations.values():
found = subcommand
break
return found
parent: Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]] = None
if not qualified_name:
return None
if " " not in qualified_name:
return get_parent_command(qualified_name)
for command_name in qualified_name.split(" "):
if parent is None:
parent = get_parent_command(command_name)
else:
parent = find_children(parent, command_name)
return parent
def get_guild_application_commands(
self, guild_id: Optional[int] = None, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that have the given guild ID. If guild_id is None, all guild commands are returned. if
rollout is True, guild_ids_to_rollout is used.
"""
return [
app_cmd
for app_cmd in self.application_commands
if guild_id is None
or guild_id in app_cmd.guild_ids
or (rollout and guild_id in app_cmd.guild_ids_to_rollout)
]
def get_global_application_commands(
self, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that are registered globally. If rollout is True, is_global is used."""
return [
app_cmd
for app_cmd in self.application_commands
if (rollout and app_cmd.is_global) or None in app_cmd.command_ids
]
def add_application_command(
self,
command: BaseApplicationCommand,
*,
overwrite: bool = False,
use_rollout: bool = False,
pre_remove: bool = True,
) -> None:
"""Adds the command to the state and updates the state with any changes made to the command.
Removes all existing references, then adds them.
Safe to call multiple times on the same application command.
Parameters
----------
command: :class:`BaseApplicationCommand`
The command to add/update the state with.
overwrite: :class:`bool`
If the library will let you add a command that overlaps with an existing command. Default ``False``.
use_rollout: :class:`bool`
If the command should be added to the state with its rollout guild IDs.
pre_remove: :class:`bool`
If the command should be removed before adding it. This will clear all signatures from storage, including
rollout ones.
"""
if pre_remove:
self.remove_application_command(command)
signature_set = (
command.get_rollout_signatures() if use_rollout else command.get_signatures()
)
for signature in signature_set:
if not overwrite and (
found_command := self._application_command_signatures.get(signature, None)
):
if found_command is not command:
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate "
f"signatures."
)
# No else because we do not care if the command has its own signature already in.
else:
self._application_command_signatures[signature] = command
for command_id in command.command_ids.values():
# PyCharm flags found_command as it "might be referenced before assignment", but that can't happen due to it
# being in an AND statement.
# noinspection PyUnboundLocalVariable
if (
not overwrite
and (found_command := self._application_command_ids.get(command_id, None))
and found_command is not command
):
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate IDs."
)
self._application_command_ids[command_id] = command
# TODO: Add the command to guilds. Should it? Check if it does in the Guild add.
self._application_commands.add(command)
def remove_application_command(self, command: BaseApplicationCommand) -> None:
"""Removes the command and all signatures + associated IDs from the state.
Safe to call with commands that aren't in the state.
Parameters
----------
command: :class:`BaseApplicationCommand`
the command to remove from the state.
"""
signature_set = command.get_rollout_signatures()
for signature in signature_set:
self._application_command_signatures.pop(signature, None)
for cmd_id in command.command_ids.values():
self._application_command_ids.pop(cmd_id, None)
self._application_commands.discard(command)
def add_all_rollout_signatures(self) -> None:
"""This adds all command signatures for rollouts to the signature cache."""
for command in self._application_commands:
self.add_application_command(command, use_rollout=True)
async def sync_all_application_commands(
self,
data: Optional[Dict[Optional[int], List[ApplicationCommandPayload]]] = None,
*,
use_rollout: bool = True,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
ignore_forbidden: bool = True,
):
"""|coro|
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and
syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many
commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare
banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause
your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see :func:`Client.sync_application_commands`
Parameters
----------
data: Optional[Dict[Optional[:class:`int`], List[:class:`dict`]]]
Data to use when comparing local application commands to what Discord has. The key should be the
:class:`int` guild ID (`None` for global) corresponding to the value list of application command payloads
from Discord. Any guild ID's not provided will be fetched if needed. Defaults to ``None``
use_rollout: :class:`bool`
If the rollout guild IDs of commands should be used. Defaults to ``True``
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``
ignore_forbidden: :class:`bool`
If this command should raise an :class:`errors.Forbidden` exception when the bot encounters a guild where
it doesn't have permissions to view application commands.
Defaults to ``True``
"""
_log.debug("Beginning sync of all application commands.")
self._get_client().add_all_application_commands()
data = {} if data is None else data.copy()
if self.application_id is None:
raise TypeError("Could not get the current application's id")
for app_cmd in self.application_commands:
self.add_application_command(command=app_cmd, use_rollout=use_rollout)
if app_cmd.is_global and None not in data:
data[None] = await self.http.get_global_commands(self.application_id)
_log.debug("Fetched global application command data.")
if app_cmd.is_guild:
for guild_id in app_cmd.guild_ids_to_rollout if use_rollout else app_cmd.guild_ids:
if guild_id not in data:
try:
data[guild_id] = await self.http.get_guild_commands(
self.application_id, guild_id
)
_log.debug(
"Fetched guild application command data for guild ID %s", guild_id
)
except Forbidden as e:
if ignore_forbidden:
_log.warning(
"nextcord.Client: Forbidden error for %s, is the applications.commands "
"Oauth scope enabled? %s",
guild_id,
e,
)
else:
raise e
for guild_id in data:
_log.debug("Running sync for %s", "global" if guild_id is None else f"Guild {guild_id}")
await self.sync_application_commands(
data=data[guild_id],
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs
global commands if the guild_id is ``None``.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
_log.debug("Syncing commands to %s", guild_id)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
if not data:
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=data, guild_id=guild_id)
_log.debug("Command sync with Guild %s finished.", guild_id)
async def discover_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
"""|coro|
Associates existing, deletes unknown, and updates modified commands for either global commands or a specific
guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Parameters
----------
data: Optional[List[:class:`dict]]
Payload from ``HTTPClient.get_guild_commands`` or ``HTTPClient.get_global_commands`` to deploy with. If None,
the payload will be retrieved from Discord.
guild_id: Optional[:class:`int`]
Guild ID to deploy application commands to. If ``None``, global commands are deployed to.
associate_known: :class:`bool`
If True, commands on Discord that pass a signature check and a deep check will be associated with locally
added ApplicationCommand objects.
delete_unknown: :class:`bool`
If ``True``, commands on Discord that fail a signature check will be removed. If ``update_known`` is False,
commands that pass the signature check but fail the deep check will also be removed.
update_known: :class:`bool`
If ``True``, commands on Discord that pass a signature check but fail the deep check will be updated.
"""
if not associate_known and not delete_unknown and not update_known:
# If everything is disabled, there is no point in doing anything.
return
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
if not data:
if guild_id:
# we do not care about typeddict specificity here
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
for raw_response in data:
payload_type = raw_response["type"] if "type" in raw_response else 1
fixed_guild_id = raw_response.get("guild_id", None)
response_signature = {
"type": int(payload_type),
"qualified_name": raw_response["name"],
"guild_id": None if not fixed_guild_id else int(fixed_guild_id),
}
app_cmd = self.get_application_command_from_signature(**response_signature)
if app_cmd:
if not isinstance(app_cmd, BaseApplicationCommand):
raise ValueError(
(
f".get_application_command_from_signature with kwargs: {response_signature} "
f"returned {type(app_cmd)} but BaseApplicationCommand was expected."
)
)
if app_cmd.is_payload_valid(raw_response, guild_id):
if associate_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s associated with added command.",
response_signature,
)
app_cmd.parse_discord_response(self, raw_response)
self.add_application_command(app_cmd, use_rollout=True)
elif update_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, updating.",
response_signature,
)
await self.register_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
# TODO: Re-examine how worthwhile this is.
await self.delete_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, raw_response["id"]
)
else:
await self.http.delete_global_command(self.application_id, raw_response["id"])
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
warnings.warn(
".deploy_application_commands is deprecated, use .discover_application_commands instead.",
stacklevel=2,
category=FutureWarning,
)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".associate_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=True,
delete_unknown=False,
update_known=False,
)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".delete_unknown_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=True,
update_known=False,
)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".update_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=False,
update_known=True,
)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers locally added application commands that don't match a signature that Discord has registered for
either global commands or a specific guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
"""
if not data:
if self.application_id is None:
raise TypeError("Could not get the current application id")
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
data_signatures = [
(
raw_response["name"],
int(raw_response["type"] if "type" in raw_response else 1),
int(temp) if (temp := raw_response.get("guild_id", None)) else temp,
)
for raw_response in data
]
# add_application_command can change the size of the dictionary, and apparently .items() doesn't prevent that
# "RuntimeError: dictionary changed size during iteration" from happening. So a copy is made for just this.
for signature, app_cmd in self._application_command_signatures.copy().items():
if (
signature not in data_signatures and signature[2] == guild_id
): # index 2 of the tuple is the guild ID.
await self.register_application_command(app_cmd, guild_id)
async def register_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers the given application command either for a specific guild or globally and adds the command to the bot.
Parameters
----------
command: :class:`BaseApplicationCommand`
Application command to register.
guild_id: Optional[:class:`int`]
ID of the guild to register the application commands to. If set to ``None``, the commands will be registered
as global commands instead. Defaults to ``None``.
"""
payload: EditApplicationCommand = command.get_payload(guild_id) # type: ignore
_log.info(
"nextcord.ConnectionState: Registering command with signature %s",
command.get_signature(guild_id),
)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
try:
if guild_id:
raw_response = await self.http.upsert_guild_command(
self.application_id, guild_id, payload
)
else:
raw_response = await self.http.upsert_global_command(self.application_id, payload)
except Exception as e:
_log.error("Error registering command %s: %s", command.error_name, e)
raise e
command.parse_discord_response(self, raw_response)
self.add_application_command(command, pre_remove=False)
async def delete_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Deletes the given application from Discord for the given guild ID or globally, then removes the signature and
command ID from the cache if possible.
Parameters
----------
command: :class:`ApplicationCommand`
Application command to delete.
guild_id: Optional[:class:`int`]
Guild ID to delete the application commands from. If ``None``, the command is deleted from global.
"""
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
try:
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, command.command_ids[guild_id]
)
else:
await self.http.delete_global_command(
self.application_id, command.command_ids[guild_id]
)
self._application_command_ids.pop(command.command_ids[guild_id], None)
self._application_command_signatures.pop(command.get_signature(guild_id), None)
except KeyError as e:
if guild_id:
_log.error(
"Could not globally unregister command %s "
"as it is not registered in the provided guild.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, "
"as it is not registered in the provided guild."
) from e
_log.error(
"Could not globally unregister command %s as it is not a global command.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, as it is not a global command."
) from e
except Exception as e:
_log.error("Error unregistering command %s: %s", command.error_name, e)
raise e
# async def register_bulk_application_commands(self) -> None:
# # TODO: Using Bulk upsert seems to delete all commands
# # It might be good to keep this around as a reminder for future work. Bulk upsert seem to delete everything
# # that isn't part of that bulk upsert, for both global and guild commands. While useful, this will
# # update/overwrite existing commands, which may (needs testing) wipe out all permissions associated with those
# # commands. Look for an opportunity to use bulk upsert.
# raise NotImplementedError
async def chunker(
self,
guild_id: int,
query: str = "",
limit: int = 0,
presences: bool = False,
*,
nonce: Optional[str] = None,
) -> None:
ws = self._get_websocket(guild_id) # This is ignored upstream
await ws.request_chunks(
guild_id, query=query, limit=limit, presences=presences, nonce=nonce
)
async def query_members(
self,
guild: Guild,
query: Optional[str],
limit: int,
user_ids: Optional[List[int]],
cache: bool,
presences: bool,
) -> List[Member]:
guild_id = guild.id
ws = self._get_websocket(guild_id)
if ws is None: # pyright: ignore[reportUnnecessaryComparison]
raise RuntimeError("Somehow do not have a websocket for this guild_id")
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request
try:
# start the query operation
await ws.request_chunks(
guild_id,
query=query,
limit=limit,
user_ids=user_ids,
presences=presences,
nonce=request.nonce,
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
_log.warning(
"Timed out waiting for chunks with query %r and limit %d for guild_id %d",
query,
limit,
guild_id,
)
raise
async def _delay_ready(self) -> None:
try:
states = []
while True:
# this snippet of code is basically waiting N seconds
# until the last GUILD_CREATE was sent
try:
guild = await asyncio.wait_for(
self._ready_state.get(), timeout=self.guild_ready_timeout
)
except asyncio.TimeoutError:
break
else:
if self._guild_needs_chunking(guild):
future = await self.chunk_guild(guild, wait=False)
states.append((guild, future))
elif guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
for guild, future in states:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
_log.warning(
"Shard ID %s timed out waiting for chunks for guild_id %s.",
guild.shard_id,
guild.id,
)
if guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
# remove the state
# AttributeError: already been deleted somehow
with contextlib.suppress(AttributeError):
del self._ready_state
except asyncio.CancelledError:
pass
else:
# dispatch the event
self.call_handlers("ready")
self.dispatch("ready")
finally:
self._ready_task = None
def parse_ready(self, data) -> None:
if self._ready_task is not None:
self._ready_task.cancel()
self._ready_state = asyncio.Queue()
self.clear(views=False)
self.user = ClientUser(state=self, data=data["user"])
self.store_user(data["user"])
if self.application_id is None:
try:
application = data["application"]
except KeyError:
pass
else:
self.application_id = utils.get_as_snowflake(application, "id")
# flags will always be present here
self.application_flags = ApplicationFlags._from_value(application["flags"])
for guild_data in data["guilds"]:
self._add_guild_from_data(guild_data)
self.dispatch("connect")
self._ready_task = asyncio.create_task(self._delay_ready())
def parse_resumed(self, data) -> None:
self.dispatch("resumed")
def parse_message_create(self, data) -> None:
channel, _ = self._get_guild_channel(data)
# channel would be the correct type here
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch("message", message)
if self._messages is not None:
self._messages.append(message)
# we ensure that the channel is either a TextChannel, ForumChannel, Thread or VoiceChannel
if channel and channel.__class__ in (TextChannel, ForumChannel, Thread, VoiceChannel):
channel.last_message_id = message.id # type: ignore
def parse_message_delete(self, data) -> None:
raw = RawMessageDeleteEvent(data)
found = self._get_message(raw.message_id)
raw.cached_message = found
self.dispatch("raw_message_delete", raw)
if self._messages is not None and found is not None:
self.dispatch("message_delete", found)
self._messages.remove(found)
def parse_message_delete_bulk(self, data) -> None:
raw = RawBulkMessageDeleteEvent(data)
if self._messages:
found_messages = [
message for message in self._messages if message.id in raw.message_ids
]
else:
found_messages = []
raw.cached_messages = found_messages
self.dispatch("raw_bulk_message_delete", raw)
if found_messages:
self.dispatch("bulk_message_delete", found_messages)
for msg in found_messages:
# self._messages won't be None here
self._messages.remove(msg) # type: ignore
def parse_message_update(self, data) -> None:
raw = RawMessageUpdateEvent(data)
message = self._get_message(raw.message_id)
if message is not None:
older_message = copy.copy(message)
raw.cached_message = older_message
self.dispatch("raw_message_edit", raw)
message._update(data)
# Coerce the `after` parameter to take the new updated Member
# ref: #5999
older_message.author = message.author
self.dispatch("message_edit", older_message, message)
else:
self.dispatch("raw_message_edit", raw)
if "components" in data and self._view_store.is_message_tracked(raw.message_id):
self._view_store.update_from_message(raw.message_id, data["components"])
def parse_message_reaction_add(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(
self, id=emoji_id, animated=emoji.get("animated", False), name=emoji["name"]
)
raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_reaction_add", raw)
# rich interface here
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
reaction = message._add_reaction(data, emoji, raw.user_id)
user = raw.member or self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_add", reaction, user)
def parse_message_reaction_remove_all(self, data) -> None:
raw = RawReactionClearEvent(data)
self.dispatch("raw_reaction_clear", raw)
message = self._get_message(raw.message_id)
if message is not None:
old_reactions = message.reactions.copy()
message.reactions.clear()
self.dispatch("reaction_clear", message, old_reactions)
def parse_message_reaction_remove(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionActionEvent(data, emoji, "REACTION_REMOVE")
self.dispatch("raw_reaction_remove", raw)
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
try:
reaction = message._remove_reaction(data, emoji, raw.user_id)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
user = self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_remove", reaction, user)
def parse_message_reaction_remove_emoji(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionClearEmojiEvent(data, emoji)
self.dispatch("raw_reaction_clear_emoji", raw)
message = self._get_message(raw.message_id)
if message is not None:
try:
reaction = message._clear_emoji(emoji)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
if reaction:
self.dispatch("reaction_clear_emoji", reaction)
def parse_interaction_create(self, data) -> None:
interaction = self._get_client().get_interaction(data=data)
if data["type"] == 3: # interaction component
custom_id = interaction.data["custom_id"] # type: ignore
component_type = interaction.data["component_type"] # type: ignore
self._view_store.dispatch(component_type, custom_id, interaction)
if data["type"] == 5: # modal submit
custom_id = interaction.data["custom_id"] # type: ignore
# key exists if type is 5 etc
self._modal_store.dispatch(custom_id, interaction)
self.dispatch("interaction", interaction)
def parse_presence_update(self, data) -> None:
guild_id = utils.get_as_snowflake(data, "guild_id")
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
user = data["user"]
member_id = int(user["id"])
member = guild.get_member(member_id)
if member is None:
_log.debug(
"PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding", member_id
)
return
old_member = Member._copy(member)
user_update = member._presence_update(data=data, user=user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("presence_update", old_member, member)
def parse_user_update(self, data) -> None:
# self.user is *always* cached when this is called
user: ClientUser = self.user # type: ignore
user._update(data)
ref = self._users.get(user.id)
if ref:
ref._update(data)
def parse_invite_create(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_create", invite)
def parse_invite_delete(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_delete", invite)
def parse_channel_delete(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = int(data["id"])
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
guild._remove_channel(channel)
self.dispatch("guild_channel_delete", channel)
def parse_channel_update(self, data) -> None:
channel_type = try_enum(ChannelType, data.get("type"))
channel_id = int(data["id"])
if channel_type is ChannelType.group:
channel = self._get_private_channel(channel_id)
old_channel = copy.copy(channel)
# the channel is a GroupChannel
channel._update_group(data) # type: ignore
self.dispatch("private_channel_update", old_channel, channel)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
old_channel = copy.copy(channel)
channel._update(guild, data)
self.dispatch("guild_channel_update", old_channel, channel)
else:
_log.debug(
"CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
else:
_log.debug("CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
def parse_channel_create(self, data) -> None:
factory, _ = _channel_factory(data["type"])
if factory is None:
_log.debug(
"CHANNEL_CREATE referencing an unknown channel type %s. Discarding.", data["type"]
)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
# the factory can't be a DMChannel or GroupChannel here
channel = factory(guild=guild, state=self, data=data) # type: ignore
guild._add_channel(channel) # type: ignore
self.dispatch("guild_channel_create", channel)
else:
_log.debug("CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
def parse_channel_pins_update(self, data) -> None:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
guild = None
channel = self._get_private_channel(channel_id)
else:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
_log.debug(
"CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
return
last_pin = (
utils.parse_time(data["last_pin_timestamp"]) if data["last_pin_timestamp"] else None
)
if guild is None:
self.dispatch("private_channel_pins_update", channel, last_pin)
else:
self.dispatch("guild_channel_pins_update", channel, last_pin)
def parse_thread_create(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_CREATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
has_thread = guild.get_thread(thread.id)
guild._add_thread(thread)
if not has_thread:
# `newly_created` is documented outside of a thread's fields:
# https://discord.dev/topics/gateway-events#thread-create
if data.get("newly_created", False):
if isinstance(thread.parent, ForumChannel):
thread.parent.last_message_id = thread.id
self.dispatch("thread_create", thread)
# Avoid an unnecessary breaking change right now by dispatching `thread_join` for
# threads that were already created.
self.dispatch("thread_join", thread)
def parse_thread_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
old = copy.copy(thread)
thread._update(data)
self.dispatch("thread_update", old, thread)
else:
thread = Thread(guild=guild, state=guild._state, data=data)
guild._add_thread(thread)
self.dispatch("thread_join", thread)
def parse_thread_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_DELETE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
guild._remove_thread(thread)
self.dispatch("thread_delete", thread)
def parse_thread_list_sync(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding", guild_id)
return
try:
channel_ids = set(data["channel_ids"])
except KeyError:
# If not provided, then the entire guild is being synced
# So all previous thread data should be overwritten
previous_threads = guild._threads.copy()
guild._clear_threads()
else:
previous_threads = guild._filter_threads(channel_ids)
threads = {d["id"]: guild._store_thread(d) for d in data.get("threads", [])}
for member in data.get("members", []):
try:
# note: member['id'] is the thread_id
thread = threads[member["id"]]
except KeyError:
continue
else:
thread._add_member(ThreadMember(thread, member))
for thread in threads.values():
old = previous_threads.pop(thread.id, None)
if old is None:
self.dispatch("thread_join", thread)
for thread in previous_threads.values():
self.dispatch("thread_remove", thread)
def parse_thread_member_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
member = ThreadMember(thread, data)
thread.me = member
def parse_thread_members_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
added_members = [ThreadMember(thread, d) for d in data.get("added_members", [])]
removed_member_ids = [int(x) for x in data.get("removed_member_ids", [])]
self_id = self.self_id
for member in added_members:
if member.id != self_id:
thread._add_member(member)
self.dispatch("thread_member_join", member)
else:
thread.me = member
self.dispatch("thread_join", thread)
for member_id in removed_member_ids:
if member_id != self_id:
member = thread._pop_member(member_id)
if member is not None:
self.dispatch("thread_member_remove", member)
else:
self.dispatch("thread_remove", thread)
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = Member(guild=guild, data=data, state=self)
if self.member_cache_flags.joined:
guild._add_member(member)
with contextlib.suppress(AttributeError):
guild._member_count += 1
self.dispatch("member_join", member)
def parse_guild_member_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
with contextlib.suppress(AttributeError):
guild._member_count -= 1
user_id = int(data["user"]["id"])
member = guild.get_member(user_id)
if member is not None:
guild._remove_member(member)
self.dispatch("member_remove", member)
else:
_log.debug(
(
"GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s."
"Falling back to raw data."
),
data["guild_id"],
)
raw = RawMemberRemoveEvent(data=data, state=self)
self.dispatch("raw_member_remove", raw)
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user = data["user"]
user_id = int(user["id"])
if guild is None:
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = guild.get_member(user_id)
if member is not None:
old_member = Member._copy(member)
member._update(data)
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("member_update", old_member, member)
else:
if self.member_cache_flags.joined:
member = Member(data=data, guild=guild, state=self)
# Force an update on the inner user if necessary
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
guild._add_member(member)
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.", user_id
)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_emojis = guild.emojis
for emoji in before_emojis:
self._emojis.pop(emoji.id, None)
guild.emojis = tuple([self.store_emoji(guild, d) for d in data["emojis"]])
self.dispatch("guild_emojis_update", guild, before_emojis, guild.emojis)
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_stickers = guild.stickers
for emoji in before_stickers:
self._stickers.pop(emoji.id, None)
guild.stickers = tuple([self.store_sticker(guild, d) for d in data["stickers"]])
self.dispatch("guild_stickers_update", guild, before_stickers, guild.stickers)
def _get_create_guild(self, data):
if data.get("unavailable") is False:
# GUILD_CREATE with unavailable in the response
# usually means that the guild has become available
# and is therefore in the cache
guild = self._get_guild(int(data["id"]))
if guild is not None:
guild.unavailable = False
guild._from_data(data)
return guild
return self._add_guild_from_data(data)
def is_guild_evicted(self, guild) -> bool:
return guild.id not in self._guilds
async def chunk_guild(self, guild, *, wait: bool = True, cache=None):
if cache is None:
cache = self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id)
if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce)
if wait:
return await request.wait()
return request.get_future()
async def _chunk_and_dispatch(self, guild, unavailable) -> None:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
_log.info("Somehow timed out waiting for chunks.")
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_create(self, data) -> None:
unavailable = data.get("unavailable")
if unavailable is True:
# joined a guild with unavailable == True so..
return
guild = self._get_create_guild(data)
try:
# Notify the on_ready state, if any, that this guild is complete.
self._ready_state.put_nowait(guild)
except AttributeError:
pass
else:
# If we're waiting for the event, put the rest on hold
return
# check if it requires chunking
if self._guild_needs_chunking(guild):
task = asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))
self._chunk_tasks[guild.id] = task
task.add_done_callback(lambda _t: self._chunk_tasks.pop(guild.id, None))
return
# Dispatch available if newly available
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_update(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is not None:
old_guild = copy.copy(guild)
guild._from_data(data)
self.dispatch("guild_update", old_guild, guild)
else:
_log.debug("GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.", data["id"])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is None:
_log.debug("GUILD_DELETE referencing an unknown guild ID: %s. Discarding.", data["id"])
return
if data.get("unavailable", False):
# GUILD_DELETE with unavailable being True means that the
# guild that was available is now currently unavailable
guild.unavailable = True
self.dispatch("guild_unavailable", guild)
return
# do a cleanup of the messages cache
if self._messages is not None:
self._messages: Optional[Deque[Message]] = deque(
(msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages
)
self._remove_guild(guild)
self.dispatch("guild_remove", guild)
def parse_guild_ban_add(self, data) -> None:
# we make the assumption that GUILD_BAN_ADD is done
# before GUILD_MEMBER_REMOVE is called
# hence we don't remove it from cache or do anything
# strange with it, the main purpose of this event
# is mainly to dispatch to another event worth listening to for logging
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
user = User(data=data["user"], state=self)
except KeyError:
pass
else:
member = guild.get_member(user.id) or user
self.dispatch("member_ban", guild, member)
def parse_guild_ban_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None and "user" in data:
user = self.store_user(data["user"])
self.dispatch("member_unban", guild, user)
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
role_data = data["role"]
role = Role(guild=guild, data=role_data, state=self)
guild._add_role(role)
self.dispatch("guild_role_create", role)
def parse_guild_role_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_id = int(data["role_id"])
try:
role = guild._remove_role(role_id)
except KeyError:
return
else:
self.dispatch("guild_role_delete", role)
else:
_log.debug(
"GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_data = data["role"]
role_id = int(role_data["id"])
role = guild.get_role(role_id)
if role is not None:
old_role = copy.copy(role)
role._update(role_data)
self.dispatch("guild_role_update", old_role, role)
else:
_log.debug(
"GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
presences = data.get("presences", [])
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get("members", [])] # type: ignore
_log.debug("Processed a chunk for %s members in guild ID %s.", len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
for presence in presences:
user = presence["user"]
member_id = user["id"]
member = member_dict.get(member_id)
if member is not None:
member._presence_update(presence, user)
complete = data.get("chunk_index", 0) + 1 == data.get("chunk_count")
self.process_chunk_requests(guild_id, data.get("nonce"), members, complete)
def parse_guild_integrations_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
self.dispatch("guild_integrations_update", guild)
else:
_log.debug(
"GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_create", integration)
else:
_log.debug(
"INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_update", integration)
else:
_log.debug(
"INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is not None:
raw = RawIntegrationDeleteEvent(data)
self.dispatch("raw_integration_delete", raw)
else:
_log.debug(
"INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding", data["guild_id"]
)
return
channel = guild.get_channel(int(data["channel_id"]))
if channel is not None:
self.dispatch("webhooks_update", channel)
else:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.",
data["channel_id"],
)
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = StageInstance(guild=guild, state=self, data=data)
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch("stage_instance_create", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = guild._stage_instances.get(int(data["id"]))
if stage_instance is not None:
old_stage_instance = copy.copy(stage_instance)
stage_instance._update(data)
self.dispatch("stage_instance_update", old_stage_instance, stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
stage_instance = guild._stage_instances.pop(int(data["id"]))
except KeyError:
pass
else:
self.dispatch("stage_instance_delete", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = utils.get_as_snowflake(data, "channel_id")
flags = self.member_cache_flags
# self.user is *always* cached when this is called
self_id = self.user.id # type: ignore
if guild is not None:
if int(data["user_id"]) == self_id:
voice = self._get_voice_client(guild.id)
if voice is not None:
coro = voice.on_voice_state_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice state update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
member, before, after = guild._update_voice_state(data, channel_id) # type: ignore
after = copy.copy(after)
if member is not None:
if flags.voice:
if channel_id is None and flags._voice_only and member.id != self_id:
# Only remove from cache if we only have the voice flag enabled
# Member doesn't meet the Snowflake protocol currently
guild._remove_member(member)
elif channel_id is not None:
guild._add_member(member)
self.dispatch("voice_state_update", member, before, after)
else:
_log.debug(
"VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.",
data["user_id"],
)
def parse_voice_server_update(self, data) -> None:
try:
key_id = int(data["guild_id"])
except KeyError:
key_id = int(data["channel_id"])
vc = self._get_voice_client(key_id)
if vc is not None:
coro = vc.on_voice_server_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice server update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
def parse_typing_start(self, data) -> None:
raw = RawTypingEvent(data)
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_typing", raw)
channel, guild = self._get_guild_channel(data)
if channel is not None: # pyright: ignore[reportUnnecessaryComparison]
user = raw.member or self._get_typing_user(channel, raw.user_id) # type: ignore
# will be messageable channel if we get here
if user is not None:
self.dispatch("typing", channel, user, raw.when)
def _get_typing_user(
self, channel: Optional[MessageableChannel], user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, DMChannel):
return channel.recipient or self.get_user(user_id)
if isinstance(channel, (Thread, TextChannel)):
return channel.guild.get_member(user_id)
if isinstance(channel, GroupChannel):
return utils.find(lambda x: x.id == user_id, channel.recipients)
return self.get_user(user_id)
def _get_reaction_user(
self, channel: MessageableChannel, user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, TextChannel):
return channel.guild.get_member(user_id)
return self.get_user(user_id)
def get_reaction_emoji(self, data) -> Union[Emoji, PartialEmoji]:
emoji_id = utils.get_as_snowflake(data, "id")
if not emoji_id:
return data["name"]
try:
return self._emojis[emoji_id]
except KeyError:
return PartialEmoji.with_state(
self, animated=data.get("animated", False), id=emoji_id, name=data["name"]
)
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:
emoji_id = emoji.id
if not emoji_id:
return emoji.name
try:
return self._emojis[emoji_id]
except KeyError:
return emoji
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel
return None
def get_scheduled_event(self, id: int) -> Optional[ScheduledEvent]:
for guild in self.guilds:
if event := guild.get_scheduled_event(id):
return event
return None
def create_message(
self,
*,
channel: MessageableChannel,
data: MessagePayload,
) -> Message:
return Message(state=self, channel=channel, data=data)
def create_scheduled_event(
self, *, guild: Guild, data: ScheduledEventPayload
) -> ScheduledEvent:
return ScheduledEvent(state=self, guild=guild, data=data)
def parse_guild_scheduled_event_create(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
event = self.create_scheduled_event(guild=guild, data=data)
guild._add_scheduled_event(event)
self.dispatch("guild_scheduled_event_create", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_update(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
old = copy.copy(event)
event._update(data)
self.dispatch("guild_scheduled_event_update", old, event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_delete(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
guild._remove_scheduled_event(event.id)
self.dispatch("guild_scheduled_event_delete", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_add(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
u = ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
)
event._add_user(u)
self.dispatch("guild_scheduled_event_user_add", event, u)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_remove(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
event._remove_user(int(data["user_id"]))
self.dispatch(
"guild_scheduled_event_user_remove",
event,
ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
),
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_auto_moderation_rule_create(self, data) -> None:
self.dispatch(
"auto_moderation_rule_create",
AutoModerationRule(data=data, state=self),
)
def parse_auto_moderation_rule_update(self, data) -> None:
self.dispatch("auto_moderation_rule_update", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_rule_delete(self, data) -> None:
self.dispatch("auto_moderation_rule_delete", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_action_execution(self, data) -> None:
self.dispatch(
"auto_moderation_action_execution", AutoModerationActionExecution(data=data, state=self)
)
def parse_guild_audit_log_entry_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user_id = None if data.get("user_id") is None else int(data["user_id"])
user = self.get_user(user_id)
users = {} if user_id is None or user is None else {user_id: user}
if guild is not None:
entry = AuditLogEntry(auto_moderation_rules={}, users=users, data=data, guild=guild)
self.dispatch("guild_audit_log_entry_create", entry)
else:
_log.debug(
"guild_audit_log_entry_create wasn't dispatched because the guild (%r) and/or user (%r) are None!",
guild,
user,
)
def create_activity(state: ConnectionState, data: None) -> None:
... | null |
160,935 | from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, overload
from .asset import Asset
from .colour import Colour
from .enums import ActivityType, try_enum
from .partial_emoji import PartialEmoji
from .utils import get_as_snowflake
class Activity(BaseActivity):
"""Represents an activity in Discord.
This could be an activity such as streaming, playing, listening
or watching.
For memory optimisation purposes, some activities are offered in slimmed
down versions:
- :class:`Game`
- :class:`Streaming`
Attributes
----------
application_id: Optional[:class:`int`]
The application ID of the game.
name: Optional[:class:`str`]
The name of the activity.
url: Optional[:class:`str`]
A stream URL that the activity could be doing.
type: :class:`ActivityType`
The type of activity currently being done.
state: Optional[:class:`str`]
The user's current state. For example, "In Game".
details: Optional[:class:`str`]
The detail of the user's current activity.
timestamps: :class:`dict`
A dictionary of timestamps. It contains the following optional keys:
- ``start``: Corresponds to when the user started doing the
activity in milliseconds since Unix epoch.
- ``end``: Corresponds to when the user will finish doing the
activity in milliseconds since Unix epoch.
assets: :class:`dict`
A dictionary representing the images and their hover text of an activity.
It contains the following optional keys:
- ``large_image``: A string representing the ID for the large image asset.
- ``large_text``: A string representing the text when hovering over the large image asset.
- ``small_image``: A string representing the ID for the small image asset.
- ``small_text``: A string representing the text when hovering over the small image asset.
party: :class:`dict`
A dictionary representing the activity party. It contains the following optional keys:
- ``id``: A string representing the party ID.
- ``size``: A list of up to two integer elements denoting (current_size, maximum_size).
buttons: List[:class:`dict`]
A list of dictionaries representing custom buttons shown in a rich presence.
Each dictionary contains the following keys:
- ``label``: A string representing the text shown on the button.
- ``url``: A string representing the URL opened upon clicking the button.
.. versionadded:: 2.0
emoji: Optional[:class:`PartialEmoji`]
The emoji that belongs to this activity.
"""
__slots__ = (
"state",
"details",
"timestamps",
"assets",
"party",
"flags",
"sync_id",
"session_id",
"type",
"name",
"url",
"application_id",
"emoji",
"buttons",
)
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.state: Optional[str] = kwargs.pop("state", None)
self.details: Optional[str] = kwargs.pop("details", None)
self.timestamps: ActivityTimestamps = kwargs.pop("timestamps", {})
self.assets: ActivityAssets = kwargs.pop("assets", {})
self.party: ActivityParty = kwargs.pop("party", {})
self.application_id: Optional[int] = get_as_snowflake(kwargs, "application_id")
self.name: Optional[str] = kwargs.pop("name", None)
self.url: Optional[str] = kwargs.pop("url", None)
self.flags: int = kwargs.pop("flags", 0)
self.sync_id: Optional[str] = kwargs.pop("sync_id", None)
self.session_id: Optional[str] = kwargs.pop("session_id", None)
self.buttons: List[ActivityButton] = kwargs.pop("buttons", [])
activity_type = kwargs.pop("type", -1)
self.type: ActivityType = (
activity_type
if isinstance(activity_type, ActivityType)
else try_enum(ActivityType, activity_type)
)
emoji = kwargs.pop("emoji", None)
self.emoji: Optional[PartialEmoji] = (
PartialEmoji.from_dict(emoji) if emoji is not None else None
)
def __repr__(self) -> str:
attrs = (
("type", self.type),
("name", self.name),
("url", self.url),
("details", self.details),
("application_id", self.application_id),
("session_id", self.session_id),
("emoji", self.emoji),
)
inner = " ".join("%s=%r" % t for t in attrs)
return f"<Activity {inner}>"
def to_dict(self) -> Dict[str, Any]:
ret: Dict[str, Any] = {}
for attr in self.__slots__:
value = getattr(self, attr, None)
if value is None:
continue
if isinstance(value, dict) and len(value) == 0:
continue
ret[attr] = value
ret["type"] = int(self.type)
if self.emoji:
ret["emoji"] = self.emoji.to_dict()
return ret
def start(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC, if applicable."""
try:
timestamp = self.timestamps["start"] / 1000
except KeyError:
return None
else:
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
def end(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: When the user will stop doing this activity in UTC, if applicable."""
try:
timestamp = self.timestamps["end"] / 1000
except KeyError:
return None
else:
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
def large_image_url(self) -> Optional[str]:
"""Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
large_image = self.assets["large_image"]
except KeyError:
return None
else:
return Asset.BASE + f"/app-assets/{self.application_id}/{large_image}.png"
def small_image_url(self) -> Optional[str]:
"""Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable."""
if self.application_id is None:
return None
try:
small_image = self.assets["small_image"]
except KeyError:
return None
else:
return Asset.BASE + f"/app-assets/{self.application_id}/{small_image}.png"
def large_image_text(self) -> Optional[str]:
"""Optional[:class:`str`]: Returns the large image asset hover text of this activity if applicable."""
return self.assets.get("large_text", None)
def small_image_text(self) -> Optional[str]:
"""Optional[:class:`str`]: Returns the small image asset hover text of this activity if applicable."""
return self.assets.get("small_text", None)
class Game(BaseActivity):
"""A slimmed down version of :class:`Activity` that represents a Discord game.
This is typically displayed via **Playing** on the official Discord client.
.. container:: operations
.. describe:: x == y
Checks if two games are equal.
.. describe:: x != y
Checks if two games are not equal.
.. describe:: hash(x)
Returns the game's hash.
.. describe:: str(x)
Returns the game's name.
Parameters
----------
name: :class:`str`
The game's name.
Attributes
----------
name: :class:`str`
The game's name.
"""
__slots__ = ("name", "_end", "_start")
def __init__(self, name: str, **extra) -> None:
super().__init__(**extra)
self.name: str = name
try:
timestamps: ActivityTimestamps = extra["timestamps"]
except KeyError:
self._start = 0
self._end = 0
else:
self._start = timestamps.get("start", 0)
self._end = timestamps.get("end", 0)
def type(self) -> ActivityType:
""":class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`.
It always returns :attr:`ActivityType.playing`.
"""
return ActivityType.playing
def start(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: When the user started playing this game in UTC, if applicable."""
if self._start:
return datetime.datetime.fromtimestamp(self._start / 1000, tz=datetime.timezone.utc)
return None
def end(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: When the user will stop playing this game in UTC, if applicable."""
if self._end:
return datetime.datetime.fromtimestamp(self._end / 1000, tz=datetime.timezone.utc)
return None
def __str__(self) -> str:
return str(self.name)
def __repr__(self) -> str:
return f"<Game name={self.name!r}>"
def to_dict(self) -> Dict[str, Any]:
timestamps: Dict[str, Any] = {}
if self._start:
timestamps["start"] = self._start
if self._end:
timestamps["end"] = self._end
return {
"type": ActivityType.playing.value,
"name": str(self.name),
"timestamps": timestamps,
}
def __eq__(self, other: Any) -> bool:
return isinstance(other, Game) and other.name == self.name
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return hash(self.name)
class Streaming(BaseActivity):
"""A slimmed down version of :class:`Activity` that represents a Discord streaming status.
This is typically displayed via **Streaming** on the official Discord client.
.. container:: operations
.. describe:: x == y
Checks if two streams are equal.
.. describe:: x != y
Checks if two streams are not equal.
.. describe:: hash(x)
Returns the stream's hash.
.. describe:: str(x)
Returns the stream's name.
Attributes
----------
platform: Optional[:class:`str`]
Where the user is streaming from (ie. YouTube, Twitch).
.. versionadded:: 1.3
name: Optional[:class:`str`]
The stream's name.
details: Optional[:class:`str`]
An alias for :attr:`name`
game: Optional[:class:`str`]
The game being streamed.
.. versionadded:: 1.3
url: :class:`str`
The stream's URL.
assets: :class:`dict`
A dictionary comprising of similar keys than those in :attr:`Activity.assets`.
"""
__slots__ = ("platform", "name", "game", "url", "details", "assets")
def __init__(self, *, name: Optional[str], url: str, **extra: Any) -> None:
super().__init__(**extra)
self.platform: Optional[str] = name
self.name: Optional[str] = extra.pop("details", name)
self.game: Optional[str] = extra.pop("state", None)
self.url: str = url
self.details: Optional[str] = extra.pop("details", self.name) # compatibility
self.assets: ActivityAssets = extra.pop("assets", {})
def type(self) -> ActivityType:
""":class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`.
It always returns :attr:`ActivityType.streaming`.
"""
return ActivityType.streaming
def __str__(self) -> str:
return str(self.name)
def __repr__(self) -> str:
return f"<Streaming name={self.name!r}>"
def twitch_name(self):
"""Optional[:class:`str`]: If provided, the twitch name of the user streaming.
This corresponds to the ``large_image`` key of the :attr:`Streaming.assets`
dictionary if it starts with ``twitch:``. Typically set by the Discord client.
"""
try:
name = self.assets["large_image"]
except KeyError:
return None
else:
return name[7:] if name[:7] == "twitch:" else None
def to_dict(self) -> Dict[str, Any]:
ret: Dict[str, Any] = {
"type": ActivityType.streaming.value,
"name": str(self.name),
"url": str(self.url),
"assets": self.assets,
}
if self.details:
ret["details"] = self.details
return ret
def __eq__(self, other: Any) -> bool:
return isinstance(other, Streaming) and other.name == self.name and other.url == self.url
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return hash(self.name)
class Spotify:
"""Represents a Spotify listening activity from Discord. This is a special case of
:class:`Activity` that makes it easier to work with the Spotify integration.
.. container:: operations
.. describe:: x == y
Checks if two activities are equal.
.. describe:: x != y
Checks if two activities are not equal.
.. describe:: hash(x)
Returns the activity's hash.
.. describe:: str(x)
Returns the string 'Spotify'.
"""
__slots__ = (
"_state",
"_details",
"_timestamps",
"_assets",
"_party",
"_sync_id",
"_session_id",
"_created_at",
)
def __init__(self, **data) -> None:
self._state: str = data.pop("state", "")
self._details: str = data.pop("details", "")
self._timestamps: Dict[str, int] = data.pop("timestamps", {})
self._assets: ActivityAssets = data.pop("assets", {})
self._party: ActivityParty = data.pop("party", {})
self._sync_id: str = data.pop("sync_id")
self._session_id: str = data.pop("session_id")
self._created_at: Optional[float] = data.pop("created_at", None)
def type(self) -> ActivityType:
""":class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`.
It always returns :attr:`ActivityType.listening`.
"""
return ActivityType.listening
def created_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: When the user started listening in UTC.
.. versionadded:: 1.3
"""
if self._created_at is not None:
return datetime.datetime.fromtimestamp(
self._created_at / 1000, tz=datetime.timezone.utc
)
return None
def colour(self) -> Colour:
""":class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`.
There is an alias for this named :attr:`color`"""
return Colour(0x1DB954)
def color(self) -> Colour:
""":class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`.
There is an alias for this named :attr:`colour`"""
return self.colour
def to_dict(self) -> Dict[str, Any]:
return {
"flags": 48, # SYNC | PLAY
"name": "Spotify",
"assets": self._assets,
"party": self._party,
"sync_id": self._sync_id,
"session_id": self._session_id,
"timestamps": self._timestamps,
"details": self._details,
"state": self._state,
}
def name(self) -> str:
""":class:`str`: The activity's name. This will always return "Spotify"."""
return "Spotify"
def __eq__(self, other: Any) -> bool:
return (
isinstance(other, Spotify)
and other._session_id == self._session_id
and other._sync_id == self._sync_id
and other.start == self.start
)
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return hash(self._session_id)
def __str__(self) -> str:
return "Spotify"
def __repr__(self) -> str:
return f"<Spotify title={self.title!r} artist={self.artist!r} track_id={self.track_id!r}>"
def title(self) -> str:
""":class:`str`: The title of the song being played."""
return self._details
def artists(self) -> List[str]:
"""List[:class:`str`]: The artists of the song being played."""
return self._state.split("; ")
def artist(self) -> str:
""":class:`str`: The artist of the song being played.
This does not attempt to split the artist information into
multiple artists. Useful if there's only a single artist.
"""
return self._state
def album(self) -> str:
""":class:`str`: The album that the song being played belongs to."""
return self._assets.get("large_text", "")
def album_cover_url(self) -> str:
""":class:`str`: The album cover image URL from Spotify's CDN."""
large_image = self._assets.get("large_image", "")
if large_image[:8] != "spotify:":
return ""
album_image_id = large_image[8:]
return "https://i.scdn.co/image/" + album_image_id
def track_id(self) -> str:
""":class:`str`: The track ID used by Spotify to identify this song."""
return self._sync_id
def track_url(self) -> str:
""":class:`str`: The track URL to listen on Spotify.
.. versionadded:: 2.0
"""
return f"https://open.spotify.com/track/{self.track_id}"
def start(self) -> datetime.datetime:
""":class:`datetime.datetime`: When the user started playing this song in UTC."""
return datetime.datetime.fromtimestamp(
self._timestamps["start"] / 1000, tz=datetime.timezone.utc
)
def end(self) -> datetime.datetime:
""":class:`datetime.datetime`: When the user will stop playing this song in UTC."""
return datetime.datetime.fromtimestamp(
self._timestamps["end"] / 1000, tz=datetime.timezone.utc
)
def duration(self) -> datetime.timedelta:
""":class:`datetime.timedelta`: The duration of the song being played."""
return self.end - self.start
def party_id(self) -> str:
""":class:`str`: The party ID of the listening party."""
return self._party.get("id", "")
class CustomActivity(BaseActivity):
"""Represents a Custom activity from Discord.
.. container:: operations
.. describe:: x == y
Checks if two activities are equal.
.. describe:: x != y
Checks if two activities are not equal.
.. describe:: hash(x)
Returns the activity's hash.
.. describe:: str(x)
Returns the custom status text.
.. versionadded:: 1.3
Attributes
----------
name: Optional[:class:`str`]
The custom activity's name.
emoji: Optional[:class:`PartialEmoji`]
The emoji to pass to the activity, if any.
state: Optional[:class:`str`]
The custom status text. :attr:`~.CustomActivity.name` must equal "Custom Status" for this to work.
.. versionchanged:: 2.6
This falls back to :attr:`~.CustomActivity.name` if not provided.
"""
__slots__ = ("name", "emoji", "state", "_state")
def __init__(
self,
name: Optional[str],
*,
_connection_state: Optional[ConnectionState] = None,
emoji: Optional[PartialEmoji] = None,
**extra: Any,
) -> None:
super().__init__(**extra)
self._state = _connection_state
self.name: Optional[str] = name
self.state: Optional[str] = extra.pop("state", name)
if self.name == "Custom Status":
self.name = self.state
self.emoji: Optional[PartialEmoji]
if emoji is None:
self.emoji = emoji
elif isinstance(emoji, dict):
self.emoji = PartialEmoji.from_dict(emoji)
elif isinstance(emoji, str):
self.emoji = PartialEmoji(name=emoji)
elif isinstance(emoji, PartialEmoji):
self.emoji = emoji
else:
raise TypeError(
f"Expected str, PartialEmoji, or None, received {type(emoji)!r} instead."
)
if self.emoji is not None:
self.emoji._state = self._state
def type(self) -> ActivityType:
""":class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`.
It always returns :attr:`ActivityType.custom`.
"""
return ActivityType.custom
def to_dict(self) -> Dict[str, Any]:
if self.name == self.state:
o = {
"type": ActivityType.custom.value,
"state": self.name,
"name": "Custom Status",
}
else:
o = {
"type": ActivityType.custom.value,
"name": self.name,
}
if self.emoji:
o["emoji"] = self.emoji.to_dict()
return o
def __eq__(self, other: Any) -> bool:
return (
isinstance(other, CustomActivity)
and other.name == self.name
and other.emoji == self.emoji
)
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return hash((self.name, str(self.emoji)))
def __str__(self) -> str:
if self.emoji:
if self.name:
return f"{self.emoji} {self.name}"
return str(self.emoji)
return str(self.name)
def __repr__(self) -> str:
return f"<CustomActivity name={self.name!r} emoji={self.emoji!r}>"
ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify]
class ActivityType(IntEnum):
"""Specifies the type of :class:`Activity`. This is used to check how to
interpret the activity itself.
"""
unknown = -1
"""An unknown activity type. This should generally not happen."""
playing = 0
"""A "Playing" activity type."""
streaming = 1
"""A "Streaming" activity type."""
listening = 2
"""A "Listening" activity type."""
watching = 3
"""A "Watching" activity type."""
custom = 4
"""A "Custom" activity type."""
competing = 5
"""A "Competing" activity type.
.. versionadded:: 1.5
"""
def try_enum(cls: Type[T], val: Any) -> T:
"""A function that tries to turn the value into enum ``cls``.
If it fails it returns a proxy invalid value instead.
"""
try:
return cls(val)
except ValueError:
return UnknownEnumValue(name=f"unknown_{val}", value=val) # type: ignore
class ConnectionState:
if TYPE_CHECKING:
_get_websocket: Callable[..., DiscordWebSocket]
_get_client: Callable[..., Client]
_parsers: Dict[str, Callable[[Dict[str, Any]], None]]
def __init__(
self,
*,
dispatch: Callable,
handlers: Dict[str, Callable],
hooks: Dict[str, Callable],
http: HTTPClient,
loop: asyncio.AbstractEventLoop,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Status] = None,
intents: Intents = Intents.default(),
chunk_guilds_at_startup: bool = MISSING,
member_cache_flags: MemberCacheFlags = MISSING,
) -> None:
self.loop: asyncio.AbstractEventLoop = loop
self.http: HTTPClient = http
self.max_messages: Optional[int] = max_messages
if self.max_messages is not None and self.max_messages <= 0:
self.max_messages = 1000
self.dispatch: Callable = dispatch
self.handlers: Dict[str, Callable] = handlers
self.hooks: Dict[str, Callable] = hooks
self.shard_count: Optional[int] = None
self._ready_task: Optional[asyncio.Task] = None
self.application_id: Optional[int] = application_id
self.heartbeat_timeout: float = heartbeat_timeout
self.guild_ready_timeout: float = guild_ready_timeout
if self.guild_ready_timeout < 0:
raise ValueError("guild_ready_timeout cannot be negative")
if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions):
raise TypeError("allowed_mentions parameter must be AllowedMentions")
self.allowed_mentions: Optional[AllowedMentions] = allowed_mentions
self._chunk_requests: Dict[Union[int, str], ChunkRequest] = {}
self._chunk_tasks: Dict[Union[int, str], asyncio.Task[None]] = {}
self._background_tasks: Set[asyncio.Task] = set()
if activity is not None:
if not isinstance(activity, BaseActivity):
raise TypeError("activity parameter must derive from BaseActivity.")
raw_activity = activity.to_dict()
else:
raw_activity = activity
raw_status = ("invisible" if status is Status.offline else str(status)) if status else None
if not isinstance(intents, Intents):
raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
if not intents.guilds:
_log.warning("Guilds intent seems to be disabled. This may cause state related issues.")
if chunk_guilds_at_startup is MISSING:
chunk_guilds_at_startup = intents.members
self._chunk_guilds: bool = chunk_guilds_at_startup
# Ensure these two are set properly
if not intents.members and self._chunk_guilds:
raise ValueError("Intents.members must be enabled to chunk guilds at startup.")
if member_cache_flags is MISSING:
member_cache_flags = MemberCacheFlags.from_intents(intents)
else:
if not isinstance(member_cache_flags, MemberCacheFlags):
raise TypeError(
"member_cache_flags parameter must be MemberCacheFlags "
f"not {type(member_cache_flags)!r}"
)
member_cache_flags._verify_intents(intents)
self.member_cache_flags: MemberCacheFlags = member_cache_flags
self._activity: Optional[ActivityPayload] = raw_activity
self._status: Optional[str] = raw_status
self._intents: Intents = intents
# A set of all application command objects available. Set because duplicates should not exist.
self._application_commands: Set[BaseApplicationCommand] = set()
# A dictionary of all available unique command signatures. Compiled at runtime because needing to iterate
# through all application commands would take far more time. If memory is problematic, perhaps this can go?
self._application_command_signatures: Dict[
Tuple[Optional[str], int, Optional[int]], BaseApplicationCommand
] = {}
# A dictionary of Discord Application Command ID's and the ApplicationCommand object they correspond to.
self._application_command_ids: Dict[int, BaseApplicationCommand] = {}
if not intents.members or member_cache_flags._empty:
self.store_user = self.create_user
self.deref_user = self.deref_user_no_intents
self.parsers = parsers = {}
for attr, func in inspect.getmembers(self):
if attr.startswith("parse_"):
parsers[attr[6:].upper()] = func
self.clear()
def clear(self, *, views: bool = True, modals: bool = True) -> None:
self.user: Optional[ClientUser] = None
# Originally, this code used WeakValueDictionary to maintain references to the
# global user mapping.
# However, profiling showed that this came with two cons:
# 1. The __weakref__ slot caused a non-trivial increase in memory
# 2. The performance of the mapping caused store_user to be a bottleneck.
# Since this is undesirable, a mapping is now used instead with stored
# references now using a regular dictionary with eviction being done
# using __del__. Testing this for memory leaks led to no discernible leaks,
# though more testing will have to be done.
self._users: Dict[int, User] = {}
self._emojis: Dict[int, Emoji] = {}
self._stickers: Dict[int, GuildSticker] = {}
self._guilds: Dict[int, Guild] = {}
# TODO: Why aren't the above and stuff below application_commands declared in __init__?
self._application_commands = set()
# Thought about making these two weakref.WeakValueDictionary's, but the bot could theoretically be holding on
# to them in a dev-defined, which would desync the bot from itself.
self._application_command_signatures = {}
self._application_command_ids = {}
if views:
self._view_store: ViewStore = ViewStore(self)
if modals:
self._modal_store: ModalStore = ModalStore(self)
self._voice_clients: Dict[int, VoiceProtocol] = {}
# LRU of max size 128
self._private_channels: OrderedDict[int, PrivateChannel] = OrderedDict()
# extra dict to look up private channels by user id
self._private_channels_by_user: Dict[int, DMChannel] = {}
if self.max_messages is not None:
self._messages: Optional[Deque[Message]] = deque(maxlen=self.max_messages)
else:
self._messages: Optional[Deque[Message]] = None
def process_chunk_requests(
self, guild_id: int, nonce: Optional[str], members: List[Member], complete: bool
) -> None:
removed = []
for key, request in self._chunk_requests.items():
if request.guild_id == guild_id and request.nonce == nonce:
request.add_members(members)
if complete:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
func = self.handlers[key]
except KeyError:
pass
else:
func(*args, **kwargs)
async def call_hooks(self, key: str, *args: Any, **kwargs: Any) -> None:
try:
coro = self.hooks[key]
except KeyError:
pass
else:
await coro(*args, **kwargs)
def self_id(self) -> Optional[int]:
u = self.user
return u.id if u else None
def intents(self) -> Intents:
ret = Intents.none()
ret.value = self._intents.value
return ret
def voice_clients(self) -> List[VoiceProtocol]:
return list(self._voice_clients.values())
def _get_voice_client(self, guild_id: Optional[int]) -> Optional[VoiceProtocol]:
# the keys of self._voice_clients are ints
return self._voice_clients.get(guild_id) # type: ignore
def _add_voice_client(self, guild_id: int, voice: VoiceProtocol) -> None:
self._voice_clients[guild_id] = voice
def _remove_voice_client(self, guild_id: int) -> None:
self._voice_clients.pop(guild_id, None)
def _update_references(self, ws: DiscordWebSocket) -> None:
for vc in self.voice_clients:
vc.main_ws = ws # type: ignore
def store_user(self, data: UserPayload) -> User:
user_id = int(data["id"])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != "0000":
self._users[user_id] = user
user._stored = True
return user
def deref_user(self, user_id: int) -> None:
self._users.pop(user_id, None)
def create_user(self, data: Union[PartialUserPayload, UserPayload]) -> User:
return User(state=self, data=data)
def deref_user_no_intents(self, user_id: int) -> None:
return
def get_user(self, id: Optional[int]) -> Optional[User]:
# the keys of self._users are ints
return self._users.get(id) # type: ignore
def store_emoji(self, guild: Guild, data: EmojiPayload) -> Emoji:
# the id will be present here
emoji_id = int(data["id"]) # type: ignore
self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data)
return emoji
def store_sticker(self, guild: Guild, data: GuildStickerPayload) -> GuildSticker:
sticker_id = int(data["id"])
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
return sticker
def store_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.add_view(view, message_id)
def store_modal(self, modal: Modal, user_id: Optional[int] = None) -> None:
self._modal_store.add_modal(modal, user_id)
def remove_view(self, view: View, message_id: Optional[int] = None) -> None:
self._view_store.remove_view(view, message_id)
def remove_modal(self, modal: Modal) -> None:
self._modal_store.remove_modal(modal)
def prevent_view_updates_for(self, message_id: Optional[int]) -> Optional[View]:
return self._view_store.remove_message_tracking(message_id) # type: ignore
def all_views(self) -> List[View]:
return self._view_store.all_views()
def views(self, persistent: bool = True) -> List[View]:
return self._view_store.views(persistent)
def guilds(self) -> List[Guild]:
return list(self._guilds.values())
def _get_guild(self, guild_id: Optional[int]) -> Optional[Guild]:
# the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore
def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild
def _remove_guild(self, guild: Guild) -> None:
self._guilds.pop(guild.id, None)
for emoji in guild.emojis:
self._emojis.pop(emoji.id, None)
for sticker in guild.stickers:
self._stickers.pop(sticker.id, None)
del guild
def emojis(self) -> List[Emoji]:
return list(self._emojis.values())
def stickers(self) -> List[GuildSticker]:
return list(self._stickers.values())
def get_emoji(self, emoji_id: Optional[int]) -> Optional[Emoji]:
# the keys of self._emojis are ints
return self._emojis.get(emoji_id) # type: ignore
def get_sticker(self, sticker_id: Optional[int]) -> Optional[GuildSticker]:
# the keys of self._stickers are ints
return self._stickers.get(sticker_id) # type: ignore
def private_channels(self) -> List[PrivateChannel]:
return list(self._private_channels.values())
def _get_private_channel(self, channel_id: Optional[int]) -> Optional[PrivateChannel]:
try:
# the keys of self._private_channels are ints
value = self._private_channels[channel_id] # type: ignore
except KeyError:
return None
else:
self._private_channels.move_to_end(channel_id) # type: ignore
return value
def _get_private_channel_by_user(self, user_id: Optional[int]) -> Optional[DMChannel]:
# the keys of self._private_channels are ints
return self._private_channels_by_user.get(user_id) # type: ignore
def _add_private_channel(self, channel: PrivateChannel) -> None:
channel_id = channel.id
self._private_channels[channel_id] = channel
if len(self._private_channels) > 128:
_, to_remove = self._private_channels.popitem(last=False)
if isinstance(to_remove, DMChannel) and to_remove.recipient:
self._private_channels_by_user.pop(to_remove.recipient.id, None)
if isinstance(channel, DMChannel) and channel.recipient:
self._private_channels_by_user[channel.recipient.id] = channel
def add_dm_channel(self, data: DMChannelPayload) -> DMChannel:
# self.user is *always* cached when this is called
channel = DMChannel(me=self.user, state=self, data=data) # type: ignore
self._add_private_channel(channel)
return channel
def _remove_private_channel(self, channel: PrivateChannel) -> None:
self._private_channels.pop(channel.id, None)
if isinstance(channel, DMChannel):
recipient = channel.recipient
if recipient is not None:
self._private_channels_by_user.pop(recipient.id, None)
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return (
utils.find(lambda m: m.id == msg_id, reversed(self._messages))
if self._messages
else None
)
def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self)
self._add_guild(guild)
return guild
def _guild_needs_chunking(self, guild: Guild) -> bool:
# If presences are enabled then we get back the old guild.large behaviour
return (
self._chunk_guilds
and not guild.chunked
and not (self._intents.presences and not guild.large)
)
def _get_guild_channel(
self, data: MessagePayload
) -> Tuple[Union[Channel, Thread], Optional[Guild]]:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
channel = self.get_channel(channel_id)
if channel is None:
channel = DMChannel._from_message(self, channel_id)
guild = getattr(channel, "guild", None)
else:
channel = guild and guild._resolve_channel(channel_id)
return channel or PartialMessageable(state=self, id=channel_id), guild
def application_commands(self) -> Set[BaseApplicationCommand]:
"""Gets a copy of the ApplicationCommand object set. If the original is given out and modified, massive desyncs
may occur. This should be used internally as well if size-changed-during-iteration is a worry.
"""
return self._application_commands.copy()
def get_application_command(self, command_id: int) -> Optional[BaseApplicationCommand]:
return self._application_command_ids.get(command_id, None)
def get_application_command_from_signature(
self,
*,
type: int,
qualified_name: str,
guild_id: Optional[int],
search_localizations: bool = False,
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
def get_parent_command(name: str, /) -> Optional[BaseApplicationCommand]:
found = self._application_command_signatures.get((name, type, guild_id))
if not search_localizations:
return found
for command in self._application_command_signatures.values():
if command.name_localizations and name in command.name_localizations.values():
found = command
break
return found
def find_children(
parent: Union[BaseApplicationCommand, SlashApplicationSubcommand], name: str, /
) -> Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]]:
children: Dict[str, SlashApplicationSubcommand] = getattr(parent, "children", {})
if not children:
return parent
found = children.get(name)
if not search_localizations:
return found
subcommand: Union[BaseApplicationCommand, SlashApplicationSubcommand]
for subcommand in children.values():
if subcommand.name_localizations and name in subcommand.name_localizations.values():
found = subcommand
break
return found
parent: Optional[Union[BaseApplicationCommand, SlashApplicationSubcommand]] = None
if not qualified_name:
return None
if " " not in qualified_name:
return get_parent_command(qualified_name)
for command_name in qualified_name.split(" "):
if parent is None:
parent = get_parent_command(command_name)
else:
parent = find_children(parent, command_name)
return parent
def get_guild_application_commands(
self, guild_id: Optional[int] = None, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that have the given guild ID. If guild_id is None, all guild commands are returned. if
rollout is True, guild_ids_to_rollout is used.
"""
return [
app_cmd
for app_cmd in self.application_commands
if guild_id is None
or guild_id in app_cmd.guild_ids
or (rollout and guild_id in app_cmd.guild_ids_to_rollout)
]
def get_global_application_commands(
self, rollout: bool = False
) -> List[BaseApplicationCommand]:
"""Gets all commands that are registered globally. If rollout is True, is_global is used."""
return [
app_cmd
for app_cmd in self.application_commands
if (rollout and app_cmd.is_global) or None in app_cmd.command_ids
]
def add_application_command(
self,
command: BaseApplicationCommand,
*,
overwrite: bool = False,
use_rollout: bool = False,
pre_remove: bool = True,
) -> None:
"""Adds the command to the state and updates the state with any changes made to the command.
Removes all existing references, then adds them.
Safe to call multiple times on the same application command.
Parameters
----------
command: :class:`BaseApplicationCommand`
The command to add/update the state with.
overwrite: :class:`bool`
If the library will let you add a command that overlaps with an existing command. Default ``False``.
use_rollout: :class:`bool`
If the command should be added to the state with its rollout guild IDs.
pre_remove: :class:`bool`
If the command should be removed before adding it. This will clear all signatures from storage, including
rollout ones.
"""
if pre_remove:
self.remove_application_command(command)
signature_set = (
command.get_rollout_signatures() if use_rollout else command.get_signatures()
)
for signature in signature_set:
if not overwrite and (
found_command := self._application_command_signatures.get(signature, None)
):
if found_command is not command:
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate "
f"signatures."
)
# No else because we do not care if the command has its own signature already in.
else:
self._application_command_signatures[signature] = command
for command_id in command.command_ids.values():
# PyCharm flags found_command as it "might be referenced before assignment", but that can't happen due to it
# being in an AND statement.
# noinspection PyUnboundLocalVariable
if (
not overwrite
and (found_command := self._application_command_ids.get(command_id, None))
and found_command is not command
):
raise ValueError(
f"{command.error_name} You cannot add application commands with duplicate IDs."
)
self._application_command_ids[command_id] = command
# TODO: Add the command to guilds. Should it? Check if it does in the Guild add.
self._application_commands.add(command)
def remove_application_command(self, command: BaseApplicationCommand) -> None:
"""Removes the command and all signatures + associated IDs from the state.
Safe to call with commands that aren't in the state.
Parameters
----------
command: :class:`BaseApplicationCommand`
the command to remove from the state.
"""
signature_set = command.get_rollout_signatures()
for signature in signature_set:
self._application_command_signatures.pop(signature, None)
for cmd_id in command.command_ids.values():
self._application_command_ids.pop(cmd_id, None)
self._application_commands.discard(command)
def add_all_rollout_signatures(self) -> None:
"""This adds all command signatures for rollouts to the signature cache."""
for command in self._application_commands:
self.add_application_command(command, use_rollout=True)
async def sync_all_application_commands(
self,
data: Optional[Dict[Optional[int], List[ApplicationCommandPayload]]] = None,
*,
use_rollout: bool = True,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
ignore_forbidden: bool = True,
):
"""|coro|
Syncs all application commands with Discord. Will sync global commands if any commands added are global, and
syncs with all guilds that have an application command targeting them.
This may call Discord many times depending on how different guilds you have local commands for, and how many
commands Discord needs to be updated or added, which may cause your bot to be rate limited or even Cloudflare
banned in VERY extreme cases.
This may incur high CPU usage depending on how many commands you have and how complex they are, which may cause
your bot to halt while it checks local commands against the existing commands that Discord has.
For a more targeted version of this method, see :func:`Client.sync_application_commands`
Parameters
----------
data: Optional[Dict[Optional[:class:`int`], List[:class:`dict`]]]
Data to use when comparing local application commands to what Discord has. The key should be the
:class:`int` guild ID (`None` for global) corresponding to the value list of application command payloads
from Discord. Any guild ID's not provided will be fetched if needed. Defaults to ``None``
use_rollout: :class:`bool`
If the rollout guild IDs of commands should be used. Defaults to ``True``
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``
ignore_forbidden: :class:`bool`
If this command should raise an :class:`errors.Forbidden` exception when the bot encounters a guild where
it doesn't have permissions to view application commands.
Defaults to ``True``
"""
_log.debug("Beginning sync of all application commands.")
self._get_client().add_all_application_commands()
data = {} if data is None else data.copy()
if self.application_id is None:
raise TypeError("Could not get the current application's id")
for app_cmd in self.application_commands:
self.add_application_command(command=app_cmd, use_rollout=use_rollout)
if app_cmd.is_global and None not in data:
data[None] = await self.http.get_global_commands(self.application_id)
_log.debug("Fetched global application command data.")
if app_cmd.is_guild:
for guild_id in app_cmd.guild_ids_to_rollout if use_rollout else app_cmd.guild_ids:
if guild_id not in data:
try:
data[guild_id] = await self.http.get_guild_commands(
self.application_id, guild_id
)
_log.debug(
"Fetched guild application command data for guild ID %s", guild_id
)
except Forbidden as e:
if ignore_forbidden:
_log.warning(
"nextcord.Client: Forbidden error for %s, is the applications.commands "
"Oauth scope enabled? %s",
guild_id,
e,
)
else:
raise e
for guild_id in data:
_log.debug("Running sync for %s", "global" if guild_id is None else f"Guild {guild_id}")
await self.sync_application_commands(
data=data[guild_id],
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
register_new=register_new,
)
async def sync_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
register_new: bool = True,
) -> None:
"""|coro|
Syncs the locally added application commands with the Guild corresponding to the given ID, or syncs
global commands if the guild_id is ``None``.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``.
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
associate_known: :class:`bool`
If local commands that match a command already on Discord should be associated with each other.
Defaults to ``True``.
delete_unknown: :class:`bool`
If commands on Discord that don't match a local command should be deleted. Defaults to ``True``.
update_known: :class:`bool`
If commands on Discord have a basic match with a local command, but don't fully match, should be updated.
Defaults to ``True``.
register_new: :class:`bool`
If a local command that doesn't have a basic match on Discord should be added to Discord.
Defaults to ``True``.
"""
_log.debug("Syncing commands to %s", guild_id)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
if not data:
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
if register_new:
await self.register_new_application_commands(data=data, guild_id=guild_id)
_log.debug("Command sync with Guild %s finished.", guild_id)
async def discover_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
"""|coro|
Associates existing, deletes unknown, and updates modified commands for either global commands or a specific
guild. This does a deep check on found commands, which may be expensive CPU-wise.
Running this for global or the same guild multiple times at once may cause unexpected or unstable behavior.
Parameters
----------
data: Optional[List[:class:`dict]]
Payload from ``HTTPClient.get_guild_commands`` or ``HTTPClient.get_global_commands`` to deploy with. If None,
the payload will be retrieved from Discord.
guild_id: Optional[:class:`int`]
Guild ID to deploy application commands to. If ``None``, global commands are deployed to.
associate_known: :class:`bool`
If True, commands on Discord that pass a signature check and a deep check will be associated with locally
added ApplicationCommand objects.
delete_unknown: :class:`bool`
If ``True``, commands on Discord that fail a signature check will be removed. If ``update_known`` is False,
commands that pass the signature check but fail the deep check will also be removed.
update_known: :class:`bool`
If ``True``, commands on Discord that pass a signature check but fail the deep check will be updated.
"""
if not associate_known and not delete_unknown and not update_known:
# If everything is disabled, there is no point in doing anything.
return
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
if not data:
if guild_id:
# we do not care about typeddict specificity here
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
for raw_response in data:
payload_type = raw_response["type"] if "type" in raw_response else 1
fixed_guild_id = raw_response.get("guild_id", None)
response_signature = {
"type": int(payload_type),
"qualified_name": raw_response["name"],
"guild_id": None if not fixed_guild_id else int(fixed_guild_id),
}
app_cmd = self.get_application_command_from_signature(**response_signature)
if app_cmd:
if not isinstance(app_cmd, BaseApplicationCommand):
raise ValueError(
(
f".get_application_command_from_signature with kwargs: {response_signature} "
f"returned {type(app_cmd)} but BaseApplicationCommand was expected."
)
)
if app_cmd.is_payload_valid(raw_response, guild_id):
if associate_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s associated with added command.",
response_signature,
)
app_cmd.parse_discord_response(self, raw_response)
self.add_application_command(app_cmd, use_rollout=True)
elif update_known:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, updating.",
response_signature,
)
await self.register_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
# TODO: Re-examine how worthwhile this is.
await self.delete_application_command(app_cmd, guild_id)
elif delete_unknown:
_log.debug(
"nextcord.ConnectionState: Command with signature %s found but failed deep check, removing.",
response_signature,
)
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, raw_response["id"]
)
else:
await self.http.delete_global_command(self.application_id, raw_response["id"])
async def deploy_application_commands(
self,
data: Optional[List[ApplicationCommandPayload]] = None,
*,
guild_id: Optional[int] = None,
associate_known: bool = True,
delete_unknown: bool = True,
update_known: bool = True,
) -> None:
warnings.warn(
".deploy_application_commands is deprecated, use .discover_application_commands instead.",
stacklevel=2,
category=FutureWarning,
)
await self.discover_application_commands(
data=data,
guild_id=guild_id,
associate_known=associate_known,
delete_unknown=delete_unknown,
update_known=update_known,
)
async def associate_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".associate_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=True,
delete_unknown=False,
update_known=False,
)
async def delete_unknown_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".delete_unknown_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=True,
update_known=False,
)
async def update_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
warnings.warn(
".update_application_commands is deprecated, use .deploy_application_commands and set "
"kwargs in it instead.",
stacklevel=2,
category=FutureWarning,
)
await self.deploy_application_commands(
data=data,
guild_id=guild_id,
associate_known=False,
delete_unknown=False,
update_known=True,
)
async def register_new_application_commands(
self, data: Optional[List[ApplicationCommandPayload]] = None, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers locally added application commands that don't match a signature that Discord has registered for
either global commands or a specific guild.
Parameters
----------
data: Optional[List[:class:`dict`]]
Data to use when comparing local application commands to what Discord has. Should be a list of application
command data from Discord. If left as ``None``, it will be fetched if needed. Defaults to ``None``
guild_id: Optional[:class:`int`]
ID of the guild to sync application commands with. If set to ``None``, global commands will be synced instead.
Defaults to ``None``.
"""
if not data:
if self.application_id is None:
raise TypeError("Could not get the current application id")
if guild_id:
data = await self.http.get_guild_commands(self.application_id, guild_id)
else:
data = await self.http.get_global_commands(self.application_id)
data_signatures = [
(
raw_response["name"],
int(raw_response["type"] if "type" in raw_response else 1),
int(temp) if (temp := raw_response.get("guild_id", None)) else temp,
)
for raw_response in data
]
# add_application_command can change the size of the dictionary, and apparently .items() doesn't prevent that
# "RuntimeError: dictionary changed size during iteration" from happening. So a copy is made for just this.
for signature, app_cmd in self._application_command_signatures.copy().items():
if (
signature not in data_signatures and signature[2] == guild_id
): # index 2 of the tuple is the guild ID.
await self.register_application_command(app_cmd, guild_id)
async def register_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Registers the given application command either for a specific guild or globally and adds the command to the bot.
Parameters
----------
command: :class:`BaseApplicationCommand`
Application command to register.
guild_id: Optional[:class:`int`]
ID of the guild to register the application commands to. If set to ``None``, the commands will be registered
as global commands instead. Defaults to ``None``.
"""
payload: EditApplicationCommand = command.get_payload(guild_id) # type: ignore
_log.info(
"nextcord.ConnectionState: Registering command with signature %s",
command.get_signature(guild_id),
)
if self.application_id is None:
raise TypeError("Could not get the current application's id")
try:
if guild_id:
raw_response = await self.http.upsert_guild_command(
self.application_id, guild_id, payload
)
else:
raw_response = await self.http.upsert_global_command(self.application_id, payload)
except Exception as e:
_log.error("Error registering command %s: %s", command.error_name, e)
raise e
command.parse_discord_response(self, raw_response)
self.add_application_command(command, pre_remove=False)
async def delete_application_command(
self, command: BaseApplicationCommand, guild_id: Optional[int] = None
) -> None:
"""|coro|
Deletes the given application from Discord for the given guild ID or globally, then removes the signature and
command ID from the cache if possible.
Parameters
----------
command: :class:`ApplicationCommand`
Application command to delete.
guild_id: Optional[:class:`int`]
Guild ID to delete the application commands from. If ``None``, the command is deleted from global.
"""
if self.application_id is None:
raise NotImplementedError("Could not get the current application id")
try:
if guild_id:
await self.http.delete_guild_command(
self.application_id, guild_id, command.command_ids[guild_id]
)
else:
await self.http.delete_global_command(
self.application_id, command.command_ids[guild_id]
)
self._application_command_ids.pop(command.command_ids[guild_id], None)
self._application_command_signatures.pop(command.get_signature(guild_id), None)
except KeyError as e:
if guild_id:
_log.error(
"Could not globally unregister command %s "
"as it is not registered in the provided guild.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, "
"as it is not registered in the provided guild."
) from e
_log.error(
"Could not globally unregister command %s as it is not a global command.",
command.error_name,
)
raise KeyError(
"This command cannot be globally unregistered, as it is not a global command."
) from e
except Exception as e:
_log.error("Error unregistering command %s: %s", command.error_name, e)
raise e
# async def register_bulk_application_commands(self) -> None:
# # TODO: Using Bulk upsert seems to delete all commands
# # It might be good to keep this around as a reminder for future work. Bulk upsert seem to delete everything
# # that isn't part of that bulk upsert, for both global and guild commands. While useful, this will
# # update/overwrite existing commands, which may (needs testing) wipe out all permissions associated with those
# # commands. Look for an opportunity to use bulk upsert.
# raise NotImplementedError
async def chunker(
self,
guild_id: int,
query: str = "",
limit: int = 0,
presences: bool = False,
*,
nonce: Optional[str] = None,
) -> None:
ws = self._get_websocket(guild_id) # This is ignored upstream
await ws.request_chunks(
guild_id, query=query, limit=limit, presences=presences, nonce=nonce
)
async def query_members(
self,
guild: Guild,
query: Optional[str],
limit: int,
user_ids: Optional[List[int]],
cache: bool,
presences: bool,
) -> List[Member]:
guild_id = guild.id
ws = self._get_websocket(guild_id)
if ws is None: # pyright: ignore[reportUnnecessaryComparison]
raise RuntimeError("Somehow do not have a websocket for this guild_id")
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request
try:
# start the query operation
await ws.request_chunks(
guild_id,
query=query,
limit=limit,
user_ids=user_ids,
presences=presences,
nonce=request.nonce,
)
return await asyncio.wait_for(request.wait(), timeout=30.0)
except asyncio.TimeoutError:
_log.warning(
"Timed out waiting for chunks with query %r and limit %d for guild_id %d",
query,
limit,
guild_id,
)
raise
async def _delay_ready(self) -> None:
try:
states = []
while True:
# this snippet of code is basically waiting N seconds
# until the last GUILD_CREATE was sent
try:
guild = await asyncio.wait_for(
self._ready_state.get(), timeout=self.guild_ready_timeout
)
except asyncio.TimeoutError:
break
else:
if self._guild_needs_chunking(guild):
future = await self.chunk_guild(guild, wait=False)
states.append((guild, future))
elif guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
for guild, future in states:
try:
await asyncio.wait_for(future, timeout=5.0)
except asyncio.TimeoutError:
_log.warning(
"Shard ID %s timed out waiting for chunks for guild_id %s.",
guild.shard_id,
guild.id,
)
if guild.unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
# remove the state
# AttributeError: already been deleted somehow
with contextlib.suppress(AttributeError):
del self._ready_state
except asyncio.CancelledError:
pass
else:
# dispatch the event
self.call_handlers("ready")
self.dispatch("ready")
finally:
self._ready_task = None
def parse_ready(self, data) -> None:
if self._ready_task is not None:
self._ready_task.cancel()
self._ready_state = asyncio.Queue()
self.clear(views=False)
self.user = ClientUser(state=self, data=data["user"])
self.store_user(data["user"])
if self.application_id is None:
try:
application = data["application"]
except KeyError:
pass
else:
self.application_id = utils.get_as_snowflake(application, "id")
# flags will always be present here
self.application_flags = ApplicationFlags._from_value(application["flags"])
for guild_data in data["guilds"]:
self._add_guild_from_data(guild_data)
self.dispatch("connect")
self._ready_task = asyncio.create_task(self._delay_ready())
def parse_resumed(self, data) -> None:
self.dispatch("resumed")
def parse_message_create(self, data) -> None:
channel, _ = self._get_guild_channel(data)
# channel would be the correct type here
message = Message(channel=channel, data=data, state=self) # type: ignore
self.dispatch("message", message)
if self._messages is not None:
self._messages.append(message)
# we ensure that the channel is either a TextChannel, ForumChannel, Thread or VoiceChannel
if channel and channel.__class__ in (TextChannel, ForumChannel, Thread, VoiceChannel):
channel.last_message_id = message.id # type: ignore
def parse_message_delete(self, data) -> None:
raw = RawMessageDeleteEvent(data)
found = self._get_message(raw.message_id)
raw.cached_message = found
self.dispatch("raw_message_delete", raw)
if self._messages is not None and found is not None:
self.dispatch("message_delete", found)
self._messages.remove(found)
def parse_message_delete_bulk(self, data) -> None:
raw = RawBulkMessageDeleteEvent(data)
if self._messages:
found_messages = [
message for message in self._messages if message.id in raw.message_ids
]
else:
found_messages = []
raw.cached_messages = found_messages
self.dispatch("raw_bulk_message_delete", raw)
if found_messages:
self.dispatch("bulk_message_delete", found_messages)
for msg in found_messages:
# self._messages won't be None here
self._messages.remove(msg) # type: ignore
def parse_message_update(self, data) -> None:
raw = RawMessageUpdateEvent(data)
message = self._get_message(raw.message_id)
if message is not None:
older_message = copy.copy(message)
raw.cached_message = older_message
self.dispatch("raw_message_edit", raw)
message._update(data)
# Coerce the `after` parameter to take the new updated Member
# ref: #5999
older_message.author = message.author
self.dispatch("message_edit", older_message, message)
else:
self.dispatch("raw_message_edit", raw)
if "components" in data and self._view_store.is_message_tracked(raw.message_id):
self._view_store.update_from_message(raw.message_id, data["components"])
def parse_message_reaction_add(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(
self, id=emoji_id, animated=emoji.get("animated", False), name=emoji["name"]
)
raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_reaction_add", raw)
# rich interface here
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
reaction = message._add_reaction(data, emoji, raw.user_id)
user = raw.member or self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_add", reaction, user)
def parse_message_reaction_remove_all(self, data) -> None:
raw = RawReactionClearEvent(data)
self.dispatch("raw_reaction_clear", raw)
message = self._get_message(raw.message_id)
if message is not None:
old_reactions = message.reactions.copy()
message.reactions.clear()
self.dispatch("reaction_clear", message, old_reactions)
def parse_message_reaction_remove(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionActionEvent(data, emoji, "REACTION_REMOVE")
self.dispatch("raw_reaction_remove", raw)
message = self._get_message(raw.message_id)
if message is not None:
emoji = self._upgrade_partial_emoji(emoji)
try:
reaction = message._remove_reaction(data, emoji, raw.user_id)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
user = self._get_reaction_user(message.channel, raw.user_id)
if user:
self.dispatch("reaction_remove", reaction, user)
def parse_message_reaction_remove_emoji(self, data) -> None:
emoji = data["emoji"]
emoji_id = utils.get_as_snowflake(emoji, "id")
emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji["name"])
raw = RawReactionClearEmojiEvent(data, emoji)
self.dispatch("raw_reaction_clear_emoji", raw)
message = self._get_message(raw.message_id)
if message is not None:
try:
reaction = message._clear_emoji(emoji)
except (AttributeError, ValueError): # eventual consistency lol
pass
else:
if reaction:
self.dispatch("reaction_clear_emoji", reaction)
def parse_interaction_create(self, data) -> None:
interaction = self._get_client().get_interaction(data=data)
if data["type"] == 3: # interaction component
custom_id = interaction.data["custom_id"] # type: ignore
component_type = interaction.data["component_type"] # type: ignore
self._view_store.dispatch(component_type, custom_id, interaction)
if data["type"] == 5: # modal submit
custom_id = interaction.data["custom_id"] # type: ignore
# key exists if type is 5 etc
self._modal_store.dispatch(custom_id, interaction)
self.dispatch("interaction", interaction)
def parse_presence_update(self, data) -> None:
guild_id = utils.get_as_snowflake(data, "guild_id")
# guild_id won't be None here
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
user = data["user"]
member_id = int(user["id"])
member = guild.get_member(member_id)
if member is None:
_log.debug(
"PRESENCE_UPDATE referencing an unknown member ID: %s. Discarding", member_id
)
return
old_member = Member._copy(member)
user_update = member._presence_update(data=data, user=user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("presence_update", old_member, member)
def parse_user_update(self, data) -> None:
# self.user is *always* cached when this is called
user: ClientUser = self.user # type: ignore
user._update(data)
ref = self._users.get(user.id)
if ref:
ref._update(data)
def parse_invite_create(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_create", invite)
def parse_invite_delete(self, data) -> None:
invite = Invite.from_gateway(state=self, data=data)
self.dispatch("invite_delete", invite)
def parse_channel_delete(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = int(data["id"])
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
guild._remove_channel(channel)
self.dispatch("guild_channel_delete", channel)
def parse_channel_update(self, data) -> None:
channel_type = try_enum(ChannelType, data.get("type"))
channel_id = int(data["id"])
if channel_type is ChannelType.group:
channel = self._get_private_channel(channel_id)
old_channel = copy.copy(channel)
# the channel is a GroupChannel
channel._update_group(data) # type: ignore
self.dispatch("private_channel_update", old_channel, channel)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
channel = guild.get_channel(channel_id)
if channel is not None:
old_channel = copy.copy(channel)
channel._update(guild, data)
self.dispatch("guild_channel_update", old_channel, channel)
else:
_log.debug(
"CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
else:
_log.debug("CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id)
def parse_channel_create(self, data) -> None:
factory, _ = _channel_factory(data["type"])
if factory is None:
_log.debug(
"CHANNEL_CREATE referencing an unknown channel type %s. Discarding.", data["type"]
)
return
guild_id = utils.get_as_snowflake(data, "guild_id")
guild = self._get_guild(guild_id)
if guild is not None:
# the factory can't be a DMChannel or GroupChannel here
channel = factory(guild=guild, state=self, data=data) # type: ignore
guild._add_channel(channel) # type: ignore
self.dispatch("guild_channel_create", channel)
else:
_log.debug("CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id)
return
def parse_channel_pins_update(self, data) -> None:
channel_id = int(data["channel_id"])
try:
guild = self._get_guild(int(data["guild_id"]))
except KeyError:
guild = None
channel = self._get_private_channel(channel_id)
else:
channel = guild and guild._resolve_channel(channel_id)
if channel is None:
_log.debug(
"CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.", channel_id
)
return
last_pin = (
utils.parse_time(data["last_pin_timestamp"]) if data["last_pin_timestamp"] else None
)
if guild is None:
self.dispatch("private_channel_pins_update", channel, last_pin)
else:
self.dispatch("guild_channel_pins_update", channel, last_pin)
def parse_thread_create(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_CREATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread = Thread(guild=guild, state=guild._state, data=data)
has_thread = guild.get_thread(thread.id)
guild._add_thread(thread)
if not has_thread:
# `newly_created` is documented outside of a thread's fields:
# https://discord.dev/topics/gateway-events#thread-create
if data.get("newly_created", False):
if isinstance(thread.parent, ForumChannel):
thread.parent.last_message_id = thread.id
self.dispatch("thread_create", thread)
# Avoid an unnecessary breaking change right now by dispatching `thread_join` for
# threads that were already created.
self.dispatch("thread_join", thread)
def parse_thread_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
old = copy.copy(thread)
thread._update(data)
self.dispatch("thread_update", old, thread)
else:
thread = Thread(guild=guild, state=guild._state, data=data)
guild._add_thread(thread)
self.dispatch("thread_join", thread)
def parse_thread_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_DELETE referencing an unknown guild ID: %s. Discarding", guild_id)
return
thread_id = int(data["id"])
thread = guild.get_thread(thread_id)
if thread is not None:
guild._remove_thread(thread)
self.dispatch("thread_delete", thread)
def parse_thread_list_sync(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug("THREAD_LIST_SYNC referencing an unknown guild ID: %s. Discarding", guild_id)
return
try:
channel_ids = set(data["channel_ids"])
except KeyError:
# If not provided, then the entire guild is being synced
# So all previous thread data should be overwritten
previous_threads = guild._threads.copy()
guild._clear_threads()
else:
previous_threads = guild._filter_threads(channel_ids)
threads = {d["id"]: guild._store_thread(d) for d in data.get("threads", [])}
for member in data.get("members", []):
try:
# note: member['id'] is the thread_id
thread = threads[member["id"]]
except KeyError:
continue
else:
thread._add_member(ThreadMember(thread, member))
for thread in threads.values():
old = previous_threads.pop(thread.id, None)
if old is None:
self.dispatch("thread_join", thread)
for thread in previous_threads.values():
self.dispatch("thread_remove", thread)
def parse_thread_member_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBER_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
member = ThreadMember(thread, data)
thread.me = member
def parse_thread_members_update(self, data) -> None:
guild_id = int(data["guild_id"])
guild: Optional[Guild] = self._get_guild(guild_id)
if guild is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown guild ID: %s. Discarding", guild_id
)
return
thread_id = int(data["id"])
thread: Optional[Thread] = guild.get_thread(thread_id)
if thread is None:
_log.debug(
"THREAD_MEMBERS_UPDATE referencing an unknown thread ID: %s. Discarding", thread_id
)
return
added_members = [ThreadMember(thread, d) for d in data.get("added_members", [])]
removed_member_ids = [int(x) for x in data.get("removed_member_ids", [])]
self_id = self.self_id
for member in added_members:
if member.id != self_id:
thread._add_member(member)
self.dispatch("thread_member_join", member)
else:
thread.me = member
self.dispatch("thread_join", thread)
for member_id in removed_member_ids:
if member_id != self_id:
member = thread._pop_member(member_id)
if member is not None:
self.dispatch("thread_member_remove", member)
else:
self.dispatch("thread_remove", thread)
def parse_guild_member_add(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = Member(guild=guild, data=data, state=self)
if self.member_cache_flags.joined:
guild._add_member(member)
with contextlib.suppress(AttributeError):
guild._member_count += 1
self.dispatch("member_join", member)
def parse_guild_member_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
with contextlib.suppress(AttributeError):
guild._member_count -= 1
user_id = int(data["user"]["id"])
member = guild.get_member(user_id)
if member is not None:
guild._remove_member(member)
self.dispatch("member_remove", member)
else:
_log.debug(
(
"GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s."
"Falling back to raw data."
),
data["guild_id"],
)
raw = RawMemberRemoveEvent(data=data, state=self)
self.dispatch("raw_member_remove", raw)
def parse_guild_member_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user = data["user"]
user_id = int(user["id"])
if guild is None:
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
member = guild.get_member(user_id)
if member is not None:
old_member = Member._copy(member)
member._update(data)
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
self.dispatch("member_update", old_member, member)
else:
if self.member_cache_flags.joined:
member = Member(data=data, guild=guild, state=self)
# Force an update on the inner user if necessary
user_update = member._update_inner_user(user)
if user_update:
self.dispatch("user_update", user_update[0], user_update[1])
guild._add_member(member)
_log.debug(
"GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.", user_id
)
def parse_guild_emojis_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_emojis = guild.emojis
for emoji in before_emojis:
self._emojis.pop(emoji.id, None)
guild.emojis = tuple([self.store_emoji(guild, d) for d in data["emojis"]])
self.dispatch("guild_emojis_update", guild, before_emojis, guild.emojis)
def parse_guild_stickers_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_STICKERS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
before_stickers = guild.stickers
for emoji in before_stickers:
self._stickers.pop(emoji.id, None)
guild.stickers = tuple([self.store_sticker(guild, d) for d in data["stickers"]])
self.dispatch("guild_stickers_update", guild, before_stickers, guild.stickers)
def _get_create_guild(self, data):
if data.get("unavailable") is False:
# GUILD_CREATE with unavailable in the response
# usually means that the guild has become available
# and is therefore in the cache
guild = self._get_guild(int(data["id"]))
if guild is not None:
guild.unavailable = False
guild._from_data(data)
return guild
return self._add_guild_from_data(data)
def is_guild_evicted(self, guild) -> bool:
return guild.id not in self._guilds
async def chunk_guild(self, guild, *, wait: bool = True, cache=None):
if cache is None:
cache = self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id)
if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce)
if wait:
return await request.wait()
return request.get_future()
async def _chunk_and_dispatch(self, guild, unavailable) -> None:
try:
await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0)
except asyncio.TimeoutError:
_log.info("Somehow timed out waiting for chunks.")
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_create(self, data) -> None:
unavailable = data.get("unavailable")
if unavailable is True:
# joined a guild with unavailable == True so..
return
guild = self._get_create_guild(data)
try:
# Notify the on_ready state, if any, that this guild is complete.
self._ready_state.put_nowait(guild)
except AttributeError:
pass
else:
# If we're waiting for the event, put the rest on hold
return
# check if it requires chunking
if self._guild_needs_chunking(guild):
task = asyncio.create_task(self._chunk_and_dispatch(guild, unavailable))
self._chunk_tasks[guild.id] = task
task.add_done_callback(lambda _t: self._chunk_tasks.pop(guild.id, None))
return
# Dispatch available if newly available
if unavailable is False:
self.dispatch("guild_available", guild)
else:
self.dispatch("guild_join", guild)
def parse_guild_update(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is not None:
old_guild = copy.copy(guild)
guild._from_data(data)
self.dispatch("guild_update", old_guild, guild)
else:
_log.debug("GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.", data["id"])
def parse_guild_delete(self, data) -> None:
guild = self._get_guild(int(data["id"]))
if guild is None:
_log.debug("GUILD_DELETE referencing an unknown guild ID: %s. Discarding.", data["id"])
return
if data.get("unavailable", False):
# GUILD_DELETE with unavailable being True means that the
# guild that was available is now currently unavailable
guild.unavailable = True
self.dispatch("guild_unavailable", guild)
return
# do a cleanup of the messages cache
if self._messages is not None:
self._messages: Optional[Deque[Message]] = deque(
(msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages
)
self._remove_guild(guild)
self.dispatch("guild_remove", guild)
def parse_guild_ban_add(self, data) -> None:
# we make the assumption that GUILD_BAN_ADD is done
# before GUILD_MEMBER_REMOVE is called
# hence we don't remove it from cache or do anything
# strange with it, the main purpose of this event
# is mainly to dispatch to another event worth listening to for logging
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
user = User(data=data["user"], state=self)
except KeyError:
pass
else:
member = guild.get_member(user.id) or user
self.dispatch("member_ban", guild, member)
def parse_guild_ban_remove(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None and "user" in data:
user = self.store_user(data["user"])
self.dispatch("member_unban", guild, user)
def parse_guild_role_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
return
role_data = data["role"]
role = Role(guild=guild, data=role_data, state=self)
guild._add_role(role)
self.dispatch("guild_role_create", role)
def parse_guild_role_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_id = int(data["role_id"])
try:
role = guild._remove_role(role_id)
except KeyError:
return
else:
self.dispatch("guild_role_delete", role)
else:
_log.debug(
"GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_role_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
role_data = data["role"]
role_id = int(role_data["id"])
role = guild.get_role(role_id)
if role is not None:
old_role = copy.copy(role)
role._update(role_data)
self.dispatch("guild_role_update", old_role, role)
else:
_log.debug(
"GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_members_chunk(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
presences = data.get("presences", [])
# the guild won't be None here
members = [Member(guild=guild, data=member, state=self) for member in data.get("members", [])] # type: ignore
_log.debug("Processed a chunk for %s members in guild ID %s.", len(members), guild_id)
if presences:
member_dict = {str(member.id): member for member in members}
for presence in presences:
user = presence["user"]
member_id = user["id"]
member = member_dict.get(member_id)
if member is not None:
member._presence_update(presence, user)
complete = data.get("chunk_index", 0) + 1 == data.get("chunk_count")
self.process_chunk_requests(guild_id, data.get("nonce"), members, complete)
def parse_guild_integrations_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
self.dispatch("guild_integrations_update", guild)
else:
_log.debug(
"GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_integration_create(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_create", integration)
else:
_log.debug(
"INTEGRATION_CREATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_update(self, data) -> None:
guild_id = int(data.pop("guild_id"))
guild = self._get_guild(guild_id)
if guild is not None:
cls, _ = _integration_factory(data["type"])
integration = cls(data=data, guild=guild)
self.dispatch("integration_update", integration)
else:
_log.debug(
"INTEGRATION_UPDATE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_integration_delete(self, data) -> None:
guild_id = int(data["guild_id"])
guild = self._get_guild(guild_id)
if guild is not None:
raw = RawIntegrationDeleteEvent(data)
self.dispatch("raw_integration_delete", raw)
else:
_log.debug(
"INTEGRATION_DELETE referencing an unknown guild ID: %s. Discarding.", guild_id
)
def parse_webhooks_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is None:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown guild ID: %s. Discarding", data["guild_id"]
)
return
channel = guild.get_channel(int(data["channel_id"]))
if channel is not None:
self.dispatch("webhooks_update", channel)
else:
_log.debug(
"WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.",
data["channel_id"],
)
def parse_stage_instance_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = StageInstance(guild=guild, state=self, data=data)
guild._stage_instances[stage_instance.id] = stage_instance
self.dispatch("stage_instance_create", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_update(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
stage_instance = guild._stage_instances.get(int(data["id"]))
if stage_instance is not None:
old_stage_instance = copy.copy(stage_instance)
stage_instance._update(data)
self.dispatch("stage_instance_update", old_stage_instance, stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown stage instance ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"STAGE_INSTANCE_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_stage_instance_delete(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
if guild is not None:
try:
stage_instance = guild._stage_instances.pop(int(data["id"]))
except KeyError:
pass
else:
self.dispatch("stage_instance_delete", stage_instance)
else:
_log.debug(
"STAGE_INSTANCE_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_voice_state_update(self, data) -> None:
guild = self._get_guild(utils.get_as_snowflake(data, "guild_id"))
channel_id = utils.get_as_snowflake(data, "channel_id")
flags = self.member_cache_flags
# self.user is *always* cached when this is called
self_id = self.user.id # type: ignore
if guild is not None:
if int(data["user_id"]) == self_id:
voice = self._get_voice_client(guild.id)
if voice is not None:
coro = voice.on_voice_state_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice state update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
member, before, after = guild._update_voice_state(data, channel_id) # type: ignore
after = copy.copy(after)
if member is not None:
if flags.voice:
if channel_id is None and flags._voice_only and member.id != self_id:
# Only remove from cache if we only have the voice flag enabled
# Member doesn't meet the Snowflake protocol currently
guild._remove_member(member)
elif channel_id is not None:
guild._add_member(member)
self.dispatch("voice_state_update", member, before, after)
else:
_log.debug(
"VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.",
data["user_id"],
)
def parse_voice_server_update(self, data) -> None:
try:
key_id = int(data["guild_id"])
except KeyError:
key_id = int(data["channel_id"])
vc = self._get_voice_client(key_id)
if vc is not None:
coro = vc.on_voice_server_update(data)
task = asyncio.create_task(
logging_coroutine(coro, info="Voice Protocol voice server update handler")
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
def parse_typing_start(self, data) -> None:
raw = RawTypingEvent(data)
member_data = data.get("member")
if member_data:
guild = self._get_guild(raw.guild_id)
if guild is not None:
raw.member = Member(data=member_data, guild=guild, state=self)
else:
raw.member = None
else:
raw.member = None
self.dispatch("raw_typing", raw)
channel, guild = self._get_guild_channel(data)
if channel is not None: # pyright: ignore[reportUnnecessaryComparison]
user = raw.member or self._get_typing_user(channel, raw.user_id) # type: ignore
# will be messageable channel if we get here
if user is not None:
self.dispatch("typing", channel, user, raw.when)
def _get_typing_user(
self, channel: Optional[MessageableChannel], user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, DMChannel):
return channel.recipient or self.get_user(user_id)
if isinstance(channel, (Thread, TextChannel)):
return channel.guild.get_member(user_id)
if isinstance(channel, GroupChannel):
return utils.find(lambda x: x.id == user_id, channel.recipients)
return self.get_user(user_id)
def _get_reaction_user(
self, channel: MessageableChannel, user_id: int
) -> Optional[Union[User, Member]]:
if isinstance(channel, TextChannel):
return channel.guild.get_member(user_id)
return self.get_user(user_id)
def get_reaction_emoji(self, data) -> Union[Emoji, PartialEmoji]:
emoji_id = utils.get_as_snowflake(data, "id")
if not emoji_id:
return data["name"]
try:
return self._emojis[emoji_id]
except KeyError:
return PartialEmoji.with_state(
self, animated=data.get("animated", False), id=emoji_id, name=data["name"]
)
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:
emoji_id = emoji.id
if not emoji_id:
return emoji.name
try:
return self._emojis[emoji_id]
except KeyError:
return emoji
def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
if id is None:
return None
pm = self._get_private_channel(id)
if pm is not None:
return pm
for guild in self.guilds:
channel = guild._resolve_channel(id)
if channel is not None:
return channel
return None
def get_scheduled_event(self, id: int) -> Optional[ScheduledEvent]:
for guild in self.guilds:
if event := guild.get_scheduled_event(id):
return event
return None
def create_message(
self,
*,
channel: MessageableChannel,
data: MessagePayload,
) -> Message:
return Message(state=self, channel=channel, data=data)
def create_scheduled_event(
self, *, guild: Guild, data: ScheduledEventPayload
) -> ScheduledEvent:
return ScheduledEvent(state=self, guild=guild, data=data)
def parse_guild_scheduled_event_create(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
event = self.create_scheduled_event(guild=guild, data=data)
guild._add_scheduled_event(event)
self.dispatch("guild_scheduled_event_create", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_CREATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_update(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
old = copy.copy(event)
event._update(data)
self.dispatch("guild_scheduled_event_update", old, event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_UPDATE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_delete(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["id"])):
guild._remove_scheduled_event(event.id)
self.dispatch("guild_scheduled_event_delete", event)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown event ID: %s. Discarding.",
data["id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_DELETE referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_add(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
u = ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
)
event._add_user(u)
self.dispatch("guild_scheduled_event_user_add", event, u)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_ADD referencing unknown guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_guild_scheduled_event_user_remove(self, data) -> None:
if guild := self._get_guild(int(data["guild_id"])):
if event := guild.get_scheduled_event(int(data["guild_scheduled_event_id"])):
event._remove_user(int(data["user_id"]))
self.dispatch(
"guild_scheduled_event_user_remove",
event,
ScheduledEventUser.from_id(
event=event, user_id=int(data["user_id"]), state=self
),
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" event ID: %s. Discarding.",
data["user_id"],
)
else:
_log.debug(
"GUILD_SCHEDULED_EVENT_USER_REMOVE referencing unknown"
" guild ID: %s. Discarding.",
data["guild_id"],
)
def parse_auto_moderation_rule_create(self, data) -> None:
self.dispatch(
"auto_moderation_rule_create",
AutoModerationRule(data=data, state=self),
)
def parse_auto_moderation_rule_update(self, data) -> None:
self.dispatch("auto_moderation_rule_update", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_rule_delete(self, data) -> None:
self.dispatch("auto_moderation_rule_delete", AutoModerationRule(data=data, state=self))
def parse_auto_moderation_action_execution(self, data) -> None:
self.dispatch(
"auto_moderation_action_execution", AutoModerationActionExecution(data=data, state=self)
)
def parse_guild_audit_log_entry_create(self, data) -> None:
guild = self._get_guild(int(data["guild_id"]))
user_id = None if data.get("user_id") is None else int(data["user_id"])
user = self.get_user(user_id)
users = {} if user_id is None or user is None else {user_id: user}
if guild is not None:
entry = AuditLogEntry(auto_moderation_rules={}, users=users, data=data, guild=guild)
self.dispatch("guild_audit_log_entry_create", entry)
else:
_log.debug(
"guild_audit_log_entry_create wasn't dispatched because the guild (%r) and/or user (%r) are None!",
guild,
user,
)
class Activity(_BaseActivity, total=False):
state: Optional[str]
details: Optional[str]
timestamps: ActivityTimestamps
assets: ActivityAssets
party: ActivityParty
application_id: Snowflake
flags: int
emoji: Optional[ActivityEmoji]
secrets: ActivitySecrets
session_id: Optional[str]
instance: bool
buttons: List[ActivityButton]
def create_activity(
state: ConnectionState, data: Optional[ActivityPayload]
) -> Optional[ActivityTypes]:
if not data:
return None
game_type = try_enum(ActivityType, data.get("type", -1))
if game_type is ActivityType.playing:
if "application_id" in data or "session_id" in data:
return Activity(**data)
return Game(**data)
if game_type is ActivityType.custom:
if "name" in data:
return CustomActivity(_connection_state=state, **data) # type: ignore
return Activity(**data)
if game_type is ActivityType.streaming:
if "url" in data:
# the URL won't be None here
return Streaming(**data) # type: ignore
return Activity(**data)
if game_type is ActivityType.listening and "sync_id" in data and "session_id" in data:
return Spotify(**data)
return Activity(**data) | null |
160,936 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)
class CachedSlotProperty(Generic[T, T_co]):
def __init__(self, name: str, function: Callable[[T], T_co]) -> None:
self.name = name
self.function = function
self.__doc__ = function.__doc__
def __get__(self, instance: None, owner: Type[T]) -> CachedSlotProperty[T, T_co]:
...
def __get__(self, instance: T, owner: Type[T]) -> T_co:
...
def __get__(self, instance: Optional[T], owner: Type[T]) -> Any:
if instance is None:
return self
try:
return getattr(instance, self.name)
except AttributeError:
value = self.function(instance)
setattr(instance, self.name, value)
return value
def cached_slot_property(
name: str,
) -> Callable[[Callable[[T], T_co]], CachedSlotProperty[T, T_co]]:
def decorator(func: Callable[[T], T_co]) -> CachedSlotProperty[T, T_co]:
return CachedSlotProperty(name, func)
return decorator | null |
160,937 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def parse_time(timestamp: None) -> None:
... | null |
160,938 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def parse_time(timestamp: str) -> datetime.datetime:
... | null |
160,939 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]:
... | null |
160,940 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]:
if timestamp:
return datetime.datetime.fromisoformat(timestamp)
return None | null |
160,941 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
def deprecated(
instead: Optional[str] = None,
) -> Callable[[Callable[P, T]], Callable[P, T]]:
def actual_decorator(func: Callable[P, T]) -> Callable[P, T]:
@functools.wraps(func)
def decorated(*args: P.args, **kwargs: P.kwargs) -> T:
warnings.simplefilter("always", DeprecationWarning) # turn off filter
if instead:
fmt = "{0.__name__} is deprecated, use {1} instead."
else:
fmt = "{0.__name__} is deprecated."
warnings.warn(fmt.format(func, instead), stacklevel=3, category=DeprecationWarning)
warnings.simplefilter("default", DeprecationWarning) # reset filter
return func(*args, **kwargs)
return decorated
return actual_decorator | null |
160,942 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
MISSING: Any = _MissingSentinel()
class Snowflake(Protocol):
"""An ABC that details the common operations on a Discord model.
Almost all :ref:`Discord models <discord_api_models>` meet this
abstract base class.
If you want to create a snowflake on your own, consider using
:class:`.Object`.
Attributes
----------
id: :class:`int`
The model's unique ID.
"""
__slots__ = ()
id: int
class Permissions(BaseFlags):
"""Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual
bits using the properties as if they were regular bools. This allows
you to edit permissions.
.. versionchanged:: 1.3
You can now use keyword arguments to initialize :class:`Permissions`
similar to :meth:`update`.
.. container:: operations
.. describe:: x == y
Checks if two permissions are equal.
.. describe:: x != y
Checks if two permissions are not equal.
.. describe:: x <= y
Checks if a permission is a subset of another permission.
.. describe:: x >= y
Checks if a permission is a superset of another permission.
.. describe:: x < y
Checks if a permission is a strict subset of another permission.
.. describe:: x > y
Checks if a permission is a strict superset of another permission.
.. describe:: hash(x)
Return the permission's hash.
.. describe:: iter(x)
Returns an iterator of ``(perm, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
Attributes
----------
value: :class:`int`
The raw value. This value is a bit array field of a 53-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
"""
__slots__ = ()
def __init__(self, permissions: int = 0, **kwargs: bool) -> None:
if not isinstance(permissions, int):
raise TypeError(
f"Expected int parameter, received {permissions.__class__.__name__} instead."
)
self.value = permissions
for key, value in kwargs.items():
if key not in self.VALID_FLAGS:
raise TypeError(f"{key!r} is not a valid permission name.")
setattr(self, key, value)
def is_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or fewer permissions as other."""
if isinstance(other, Permissions):
return (self.value & other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions):
return (self.value | other.value) == self.value
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}")
def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self."""
return self.is_subset(other) and self != other
def is_strict_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict superset of those on self."""
return self.is_superset(other) and self != other
__le__ = is_subset
__ge__ = is_superset
__lt__ = is_strict_subset
__gt__ = is_strict_superset
def none(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``False``."""
return cls(0)
def all(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
permissions set to ``True``.
"""
return cls(-1)
def all_channel(cls) -> Self:
"""A :class:`Permissions` with all channel-specific permissions set to
``True`` and the guild-specific ones set to ``False``. The guild-specific
permissions are currently:
- :attr:`manage_emojis`
- :attr:`view_audit_log`
- :attr:`view_guild_insights`
- :attr:`manage_guild`
- :attr:`change_nickname`
- :attr:`manage_nicknames`
- :attr:`kick_members`
- :attr:`ban_members`
- :attr:`administrator`
.. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_slash_commands` permissions.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`use_external_stickers`, :attr:`send_messages_in_threads` and
:attr:`request_to_speak` permissions.
"""
return cls(0b111110110110011111101111111111101010001)
def general(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"General" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is now included in the general permissions, but
permissions :attr:`administrator`, :attr:`create_instant_invite`, :attr:`kick_members`,
:attr:`ban_members`, :attr:`change_nickname` and :attr:`manage_nicknames` are
no longer part of the general permissions.
"""
return cls(0b01110000000010000000010010110000)
def membership(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Membership" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b00001100000000000000000000000111)
def text(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Text" permissions from the official Discord UI set to ``True``.
.. versionchanged:: 1.7
Permission :attr:`read_messages` is no longer part of the text permissions.
Added :attr:`use_slash_commands` permission.
.. versionchanged:: 2.0
Added :attr:`create_public_threads`, :attr:`create_private_threads`, :attr:`manage_threads`,
:attr:`send_messages_in_threads` and :attr:`use_external_stickers` permissions.
"""
return cls(0b111110010000000000001111111100001000000)
def voice(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Voice" permissions from the official Discord UI set to ``True``."""
return cls(0b00000011111100000000001100000000)
def stage(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Channel" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 32)
def stage_moderator(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Stage Moderator" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(0b100000001010000000000000000000000)
def advanced(cls) -> Self:
"""A factory method that creates a :class:`Permissions` with all
"Advanced" permissions from the official Discord UI set to ``True``.
.. versionadded:: 1.7
"""
return cls(1 << 3)
def update(self, **kwargs: bool) -> None:
r"""Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.
Parameters
----------
\*\*kwargs
A list of key/value pairs to bulk update permissions with.
"""
for key, value in kwargs.items():
if key in self.VALID_FLAGS:
setattr(self, key, value)
def handle_overwrite(self, allow: int, deny: int) -> None:
# Basically this is what's happening here.
# We have an original bit array, e.g. 1010
# Then we have another bit array that is 'denied', e.g. 1111
# And then we have the last one which is 'allowed', e.g. 0101
# We want original OP denied to end up resulting in
# whatever is in denied to be set to 0.
# So 1010 OP 1111 -> 0000
# Then we take this value and look at the allowed values.
# And whatever is allowed is set to 1.
# So 0000 OP2 0101 -> 0101
# The OP is base & ~denied.
# The OP2 is base | allowed.
self.value = (self.value & ~deny) | allow
def create_instant_invite(self) -> int:
""":class:`bool`: Returns ``True`` if the user can create instant invites."""
return 1 << 0
def kick_members(self) -> int:
""":class:`bool`: Returns ``True`` if the user can kick users from the guild."""
return 1 << 1
def ban_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can ban users from the guild."""
return 1 << 2
def administrator(self) -> int:
""":class:`bool`: Returns ``True`` if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
"""
return 1 << 3
def manage_channels(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit, delete, or create channels in the guild.
This also corresponds to the "Manage Channel" channel-specific override."""
return 1 << 4
def manage_guild(self) -> int:
""":class:`bool`: Returns ``True`` if a user can edit guild properties."""
return 1 << 5
def add_reactions(self) -> int:
""":class:`bool`: Returns ``True`` if a user can add reactions to messages."""
return 1 << 6
def view_audit_log(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's audit log."""
return 1 << 7
def priority_speaker(self) -> int:
""":class:`bool`: Returns ``True`` if a user can be more easily heard while talking."""
return 1 << 8
def stream(self) -> int:
""":class:`bool`: Returns ``True`` if a user can stream in a voice channel."""
return 1 << 9
def read_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read messages from all or specific text channels."""
return 1 << 10
def view_channel(self) -> int:
""":class:`bool`: An alias for :attr:`read_messages`.
.. versionadded:: 1.3
"""
return 1 << 10
def send_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages from all or specific text channels.
This falls under ``Create Posts`` on the UI specifically for Forum Channels.
"""
return 1 << 11
def send_tts_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send TTS messages from all or specific text channels."""
return 1 << 12
def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete or pin messages in a text channel.
.. note::
Note that there are currently no ways to edit other people's messages.
"""
return 1 << 13
def embed_links(self) -> int:
""":class:`bool`: Returns ``True`` if a user's messages will automatically be embedded by Discord."""
return 1 << 14
def attach_files(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send files in their messages."""
return 1 << 15
def read_message_history(self) -> int:
""":class:`bool`: Returns ``True`` if a user can read a text channel's previous messages."""
return 1 << 16
def mention_everyone(self) -> int:
""":class:`bool`: Returns ``True`` if a user's @everyone or @here will mention everyone in the text channel."""
return 1 << 17
def external_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use emojis from other guilds."""
return 1 << 18
def use_external_emojis(self) -> int:
""":class:`bool`: An alias for :attr:`external_emojis`.
.. versionadded:: 1.3
"""
return 1 << 18
def view_guild_insights(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view the guild's insights.
.. versionadded:: 1.3
"""
return 1 << 19
def connect(self) -> int:
""":class:`bool`: Returns ``True`` if a user can connect to a voice channel."""
return 1 << 20
def speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can speak in a voice channel."""
return 1 << 21
def mute_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can mute other users."""
return 1 << 22
def deafen_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can deafen other users."""
return 1 << 23
def move_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can move users between other voice channels."""
return 1 << 24
def use_voice_activation(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use voice activation in voice channels."""
return 1 << 25
def change_nickname(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change their nickname in the guild."""
return 1 << 26
def manage_nicknames(self) -> int:
""":class:`bool`: Returns ``True`` if a user can change other user's nickname in the guild."""
return 1 << 27
def manage_roles(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create or edit roles less than their role's position.
This also corresponds to the "Manage Permissions" channel-specific override.
"""
return 1 << 28
def manage_permissions(self) -> int:
""":class:`bool`: An alias for :attr:`manage_roles`.
.. versionadded:: 1.3
"""
return 1 << 28
def manage_webhooks(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete webhooks."""
return 1 << 29
def manage_emojis(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create, edit, or delete emojis."""
return 1 << 30
def manage_emojis_and_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`manage_emojis`.
.. versionadded:: 2.0
"""
return 1 << 30
def use_slash_commands(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use slash commands.
.. versionadded:: 1.7
"""
return 1 << 31
def request_to_speak(self) -> int:
""":class:`bool`: Returns ``True`` if a user can request to speak in a stage channel.
.. versionadded:: 1.7
"""
return 1 << 32
def manage_events(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage guild events.
.. versionadded:: 2.0
"""
return 1 << 33
def manage_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can manage threads.
.. versionadded:: 2.0
"""
return 1 << 34
def create_public_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create public threads.
.. versionadded:: 2.0
"""
return 1 << 35
def create_private_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can create private threads.
.. versionadded:: 2.0
"""
return 1 << 36
def external_stickers(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use stickers from other guilds.
.. versionadded:: 2.0
"""
return 1 << 37
def use_external_stickers(self) -> int:
""":class:`bool`: An alias for :attr:`external_stickers`.
.. versionadded:: 2.0
"""
return 1 << 37
def send_messages_in_threads(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send messages in threads.
This falls under ``Send Messages in Posts`` on the UI specifically for Forum channels.
.. versionadded:: 2.0
"""
return 1 << 38
def start_embedded_activities(self) -> int:
""":class:`bool`: Returns ``True`` if a user can launch activities in a voice channel.
.. versionadded:: 2.0
"""
return 1 << 39
def moderate_members(self) -> int:
""":class:`bool`: Returns ``True`` if a user can moderate members (add timeouts).
Referred to as ``Timeout Members`` in the discord client.
.. versionadded:: 2.0
"""
return 1 << 40
The provided code snippet includes necessary dependencies for implementing the `oauth_url` function. Write a Python function `def oauth_url( client_id: Union[int, str], *, permissions: Permissions = MISSING, guild: Snowflake = MISSING, redirect_uri: str = MISSING, scopes: Iterable[str] = MISSING, disable_guild_select: bool = False, ) -> str` to solve the following problem:
A helper function that returns the OAuth2 URL for inviting the bot into guilds. Parameters ---------- client_id: Union[:class:`int`, :class:`str`] The client ID for your bot. permissions: :class:`~nextcord.Permissions` The permissions you're requesting. If not given then you won't be requesting any permissions. guild: :class:`~nextcord.abc.Snowflake` The guild to pre-select in the authorization screen, if available. redirect_uri: :class:`str` An optional valid redirect URI. scopes: Iterable[:class:`str`] An optional valid list of scopes. Defaults to ``('bot',)``. .. versionadded:: 1.7 disable_guild_select: :class:`bool` Whether to disallow the user from changing the guild dropdown. .. versionadded:: 2.0 Returns ------- :class:`str` The OAuth2 URL for inviting the bot into guilds.
Here is the function:
def oauth_url(
client_id: Union[int, str],
*,
permissions: Permissions = MISSING,
guild: Snowflake = MISSING,
redirect_uri: str = MISSING,
scopes: Iterable[str] = MISSING,
disable_guild_select: bool = False,
) -> str:
"""A helper function that returns the OAuth2 URL for inviting the bot
into guilds.
Parameters
----------
client_id: Union[:class:`int`, :class:`str`]
The client ID for your bot.
permissions: :class:`~nextcord.Permissions`
The permissions you're requesting. If not given then you won't be requesting any
permissions.
guild: :class:`~nextcord.abc.Snowflake`
The guild to pre-select in the authorization screen, if available.
redirect_uri: :class:`str`
An optional valid redirect URI.
scopes: Iterable[:class:`str`]
An optional valid list of scopes. Defaults to ``('bot',)``.
.. versionadded:: 1.7
disable_guild_select: :class:`bool`
Whether to disallow the user from changing the guild dropdown.
.. versionadded:: 2.0
Returns
-------
:class:`str`
The OAuth2 URL for inviting the bot into guilds.
"""
url = f"https://discord.com/oauth2/authorize?client_id={client_id}"
url += "&scope=" + "+".join(scopes or ("bot",))
if permissions is not MISSING:
url += f"&permissions={permissions.value}"
if guild is not MISSING:
url += f"&guild_id={guild.id}"
if redirect_uri is not MISSING:
from urllib.parse import urlencode
url += "&response_type=code&" + urlencode({"redirect_uri": redirect_uri})
if disable_guild_select:
url += "&disable_guild_select=true"
return url | A helper function that returns the OAuth2 URL for inviting the bot into guilds. Parameters ---------- client_id: Union[:class:`int`, :class:`str`] The client ID for your bot. permissions: :class:`~nextcord.Permissions` The permissions you're requesting. If not given then you won't be requesting any permissions. guild: :class:`~nextcord.abc.Snowflake` The guild to pre-select in the authorization screen, if available. redirect_uri: :class:`str` An optional valid redirect URI. scopes: Iterable[:class:`str`] An optional valid list of scopes. Defaults to ``('bot',)``. .. versionadded:: 1.7 disable_guild_select: :class:`bool` Whether to disallow the user from changing the guild dropdown. .. versionadded:: 2.0 Returns ------- :class:`str` The OAuth2 URL for inviting the bot into guilds. |
160,943 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
DISCORD_EPOCH = 1420070400000
The provided code snippet includes necessary dependencies for implementing the `snowflake_time` function. Write a Python function `def snowflake_time(id: int) -> datetime.datetime` to solve the following problem:
Parameters ---------- id: :class:`int` The snowflake ID. Returns ------- :class:`datetime.datetime` An aware datetime in UTC representing the creation time of the snowflake.
Here is the function:
def snowflake_time(id: int) -> datetime.datetime:
"""
Parameters
----------
id: :class:`int`
The snowflake ID.
Returns
-------
:class:`datetime.datetime`
An aware datetime in UTC representing the creation time of the snowflake.
"""
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) | Parameters ---------- id: :class:`int` The snowflake ID. Returns ------- :class:`datetime.datetime` An aware datetime in UTC representing the creation time of the snowflake. |
160,944 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
DISCORD_EPOCH = 1420070400000
The provided code snippet includes necessary dependencies for implementing the `time_snowflake` function. Write a Python function `def time_snowflake(dt: datetime.datetime, high: bool = False) -> int` to solve the following problem:
Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use ``time_snowflake(high=False) - 1`` to be inclusive, ``high=True`` to be exclusive. When using as the higher end of a range, use ``time_snowflake(high=True) + 1`` to be inclusive, ``high=False`` to be exclusive Parameters ---------- dt: :class:`datetime.datetime` A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. Returns ------- :class:`int` The snowflake representing the time given.
Here is the function:
def time_snowflake(dt: datetime.datetime, high: bool = False) -> int:
"""Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use ``time_snowflake(high=False) - 1``
to be inclusive, ``high=True`` to be exclusive.
When using as the higher end of a range, use ``time_snowflake(high=True) + 1``
to be inclusive, ``high=False`` to be exclusive
Parameters
----------
dt: :class:`datetime.datetime`
A datetime object to convert to a snowflake.
If naive, the timezone is assumed to be local time.
high: :class:`bool`
Whether or not to set the lower 22 bit to high or low.
Returns
-------
:class:`int`
The snowflake representing the time given.
"""
discord_millis = int(dt.timestamp() * 1000 - DISCORD_EPOCH)
return (discord_millis << 22) + (2**22 - 1 if high else 0) | Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use ``time_snowflake(high=False) - 1`` to be inclusive, ``high=True`` to be exclusive. When using as the higher end of a range, use ``time_snowflake(high=True) + 1`` to be inclusive, ``high=False`` to be exclusive Parameters ---------- dt: :class:`datetime.datetime` A datetime object to convert to a snowflake. If naive, the timezone is assumed to be local time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. Returns ------- :class:`int` The snowflake representing the time given. |
160,945 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
The provided code snippet includes necessary dependencies for implementing the `find` function. Write a Python function `def find(predicate: Callable[[T], Any], seq: Iterable[T]) -> Optional[T]` to solve the following problem:
A helper to return the first element found in the sequence that meets the predicate. For example: :: member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members) would find the first :class:`~nextcord.Member` whose name is 'Mighty' and return it. If an entry is not found, then ``None`` is returned. This is different from :func:`py:filter` due to the fact it stops the moment it finds a valid entry. Parameters ---------- predicate A function that returns a boolean-like result. seq: :class:`collections.abc.Iterable` The iterable to search through.
Here is the function:
def find(predicate: Callable[[T], Any], seq: Iterable[T]) -> Optional[T]:
"""A helper to return the first element found in the sequence
that meets the predicate. For example: ::
member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
would find the first :class:`~nextcord.Member` whose name is 'Mighty' and return it.
If an entry is not found, then ``None`` is returned.
This is different from :func:`py:filter` due to the fact it stops the moment it finds
a valid entry.
Parameters
----------
predicate
A function that returns a boolean-like result.
seq: :class:`collections.abc.Iterable`
The iterable to search through.
"""
for element in seq:
if predicate(element):
return element
return None | A helper to return the first element found in the sequence that meets the predicate. For example: :: member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members) would find the first :class:`~nextcord.Member` whose name is 'Mighty' and return it. If an entry is not found, then ``None`` is returned. This is different from :func:`py:filter` due to the fact it stops the moment it finds a valid entry. Parameters ---------- predicate A function that returns a boolean-like result. seq: :class:`collections.abc.Iterable` The iterable to search through. |
160,946 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
def unique(iterable: Iterable[T]) -> List[T]:
return list(dict.fromkeys(iterable)) | null |
160,947 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def get_as_snowflake(data: Any, key: str) -> Optional[int]:
try:
value = data[key]
except KeyError:
return None
else:
return value and int(value) | null |
160,948 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def _bytes_to_base64_data(data: bytes) -> str:
fmt = "data:{mime};base64,{data}"
mime = _get_mime_type_for_image(data)
b64 = b64encode(data).decode("ascii")
return fmt.format(mime=mime, data=b64)
class File:
r"""A parameter object used for :meth:`abc.Messageable.send`
for sending file objects.
.. versionchanged:: 2.5
You can now use nextcord.File as a context manager. This will
automatically call :meth:`close` when the context manager exits scope.
When using the context manager, force_close will default to True.
.. note::
File objects are single use and are not meant to be reused in
multiple :meth:`abc.Messageable.send`\s.
Parameters
----------
fp: Union[str, bytes, os.PathLike, io.BufferedIOBase]
A file-like object opened in binary mode and read mode
or a filename representing a file in the hard drive to
open.
.. note::
If the file-like object passed is opened via ``open`` then the
modes 'rb' should be used.
To pass binary data, consider usage of ``io.BytesIO``.
filename: Optional[:class:`str`]
The filename to display when uploading to Discord.
If this is not given then it defaults to ``fp.name`` or if ``fp`` is
a string then the ``filename`` will default to the string given.
description: Optional[:class:`str`]
The description for the file. This is used to display alternative text
in the Discord client.
spoiler: :class:`bool`
Whether the attachment is a spoiler.
force_close: :class:`bool`
Whether to forcibly close the bytes used to create the file
when ``.close()`` is called.
This will also make the file bytes unusable by flushing it from
memory after it is sent once.
Enable this if you don't wish to reuse the same bytes.
Defaults to ``True`` when using context manager.
.. versionadded:: 2.2
Attributes
----------
fp: Union[:class:`io.BufferedReader`, :class:`io.BufferedIOBase`]
A file-like object opened in binary mode and read mode.
This will be a :class:`io.BufferedIOBase` if an
object of type :class:`io.IOBase` was passed, or a
:class:`io.BufferedReader` if a filename was passed.
filename: Optional[:class:`str`]
The filename to display when uploading to Discord.
description: Optional[:class:`str`]
The description for the file. This is used to display alternative text
in the Discord client.
spoiler: :class:`bool`
Whether the attachment is a spoiler.
force_close: :class:`bool`
Whether to forcibly close the bytes used to create the file
when ``.close()`` is called.
This will also make the file bytes unusable by flushing it from
memory after it is sent or used once.
Enable this if you don't wish to reuse the same bytes.
.. versionadded:: 2.2
"""
__slots__ = (
"fp",
"filename",
"spoiler",
"force_close",
"_original_pos",
"_owner",
"_closer",
"description",
)
if TYPE_CHECKING:
fp: Union[io.BufferedReader, io.BufferedIOBase]
filename: Optional[str]
description: Optional[str]
spoiler: bool
force_close: Optional[bool]
def __init__(
self,
fp: Union[str, bytes, os.PathLike, io.BufferedIOBase],
filename: Optional[str] = None,
*,
description: Optional[str] = None,
spoiler: bool = False,
force_close: Optional[bool] = None,
) -> None:
if isinstance(fp, io.IOBase):
if not (fp.seekable() and fp.readable()):
raise ValueError(f"File buffer {fp!r} must be seekable and readable")
self.fp = fp
self._original_pos = fp.tell()
self._owner = False
else:
self.fp = open(fp, "rb") # noqa: SIM115
self._original_pos = 0
self._owner = True
self.force_close = force_close
# aiohttp only uses two methods from IOBase
# read and close, since I want to control when the files
# close, I need to stub it so it doesn't close unless
# I tell it to
self._closer = self.fp.close
self.fp.close = lambda: None
if filename is None:
if isinstance(fp, str):
_, self.filename = os.path.split(fp)
else:
self.filename = getattr(fp, "name", None)
else:
self.filename = filename
self.description = description
if spoiler and self.filename is not None and not self.filename.startswith("SPOILER_"):
self.filename = "SPOILER_" + self.filename
self.spoiler = spoiler or (
self.filename is not None and self.filename.startswith("SPOILER_")
)
def __enter__(self) -> File:
# Set force_close to true when using context manager
# and force_close was not provided to __init__
if self.force_close is None:
self.force_close = True
return self
def __exit__(self, *_) -> None:
self.close()
def reset(self, *, seek: Union[int, bool] = True) -> None:
# The `seek` parameter is needed because
# the retry-loop is iterated over multiple times
# starting from 0, as an implementation quirk
# the resetting must be done at the beginning
# before a request is done, since the first index
# is 0, and thus false, then this prevents an
# unnecessary seek since it's the first request
# done.
if seek:
self.fp.seek(self._original_pos)
def close(self) -> None:
self.fp.close = self._closer
if self._owner or self.force_close:
self._closer()
class Asset(AssetMixin):
"""Represents a CDN asset on Discord.
.. container:: operations
.. describe:: str(x)
Returns the URL of the CDN asset.
.. describe:: len(x)
Returns the length of the CDN asset's URL.
.. describe:: x == y
Checks if the asset is equal to another asset.
.. describe:: x != y
Checks if the asset is not equal to another asset.
.. describe:: hash(x)
Returns the hash of the asset.
"""
__slots__: Tuple[str, ...] = (
"_state",
"_url",
"_animated",
"_key",
)
BASE = "https://cdn.discordapp.com"
def __init__(self, state, *, url: str, key: str, animated: bool = False) -> None:
self._state = state
self._url = url
self._animated = animated
self._key = key
def _from_default_avatar(cls, state, index: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/embed/avatars/{index}.png",
key=str(index),
animated=False,
)
def _from_avatar(cls, state, user_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_guild_avatar(cls, state, guild_id: int, member_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
def _from_icon(cls, state, object_id: int, icon_hash: str, path: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/{path}-icons/{object_id}/{icon_hash}.png?size=1024",
key=icon_hash,
animated=False,
)
def _from_cover_image(cls, state, object_id: int, cover_image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/{object_id}/store/{cover_image_hash}.png?size=1024",
key=cover_image_hash,
animated=False,
)
def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset:
animated = False
format = "png"
if path == "banners":
animated = image.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
key=image,
animated=animated,
)
def _from_guild_icon(cls, state, guild_id: int, icon_hash: str) -> Asset:
animated = icon_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
key=icon_hash,
animated=animated,
)
def _from_sticker_banner(cls, state, banner: int) -> Asset:
return cls(
state,
url=f"{cls.BASE}/app-assets/710982414301790216/store/{banner}.png",
key=str(banner),
animated=False,
)
def _from_user_banner(cls, state, user_id: int, banner_hash: str) -> Asset:
animated = banner_hash.startswith("a_")
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
key=banner_hash,
animated=animated,
)
def _from_scheduled_event_image(cls, state, event_id: int, image_hash: str) -> Asset:
return cls(
state,
url=f"{cls.BASE}/guild-events/{event_id}/{image_hash}.png",
key=image_hash,
animated=False,
)
def __str__(self) -> str:
return self._url
def __len__(self) -> int:
return len(self._url)
def __repr__(self) -> str:
shorten = self._url.replace(self.BASE, "")
return f"<Asset url={shorten!r}>"
def __eq__(self, other):
return isinstance(other, Asset) and self._url == other._url
def __hash__(self):
return hash(self._url)
def url(self) -> str:
""":class:`str`: Returns the underlying URL of the asset."""
return self._url
def key(self) -> str:
""":class:`str`: Returns the identifying key of the asset."""
return self._key
def is_animated(self) -> bool:
""":class:`bool`: Returns whether the asset is animated."""
return self._animated
def replace(
self,
*,
size: int = MISSING,
format: ValidAssetFormatTypes = MISSING,
static_format: ValidStaticFormatTypes = MISSING,
) -> Asset:
"""Returns a new asset with the passed components replaced.
Parameters
----------
size: :class:`int`
The new size of the asset.
format: :class:`str`
The new format to change it to. Must be either
'webp', 'jpeg', 'jpg', 'png', or 'gif' if it's animated.
static_format: :class:`str`
The new format to change it to if the asset isn't animated.
Must be either 'webp', 'jpeg', 'jpg', or 'png'.
Raises
------
InvalidArgument
An invalid size or format was passed.
Returns
-------
:class:`Asset`
The newly updated asset.
"""
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
if format is not MISSING:
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
url = url.with_path(f"{path}.{format}")
elif static_format is MISSING:
if format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{format}")
if static_format is not MISSING and not self._animated:
if static_format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{static_format}")
if size is not MISSING:
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = url.with_query(size=size)
else:
url = url.with_query(url.raw_query_string)
url = str(url)
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_size(self, size: int, /) -> Asset:
"""Returns a new asset with the specified size.
Parameters
----------
size: :class:`int`
The new size of the asset.
Raises
------
InvalidArgument
The asset had an invalid size.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
url = str(yarl.URL(self._url).with_query(size=size))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_format(self, format: ValidAssetFormatTypes, /) -> Asset:
"""Returns a new asset with the specified format.
Parameters
----------
format: :class:`str`
The new format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
elif format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
url = str(url.with_path(f"{path}.{format}").with_query(url.raw_query_string))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
def with_static_format(self, format: ValidStaticFormatTypes, /) -> Asset:
"""Returns a new asset with the specified static format.
This only changes the format if the underlying asset is
not animated. Otherwise, the asset is not changed.
Parameters
----------
format: :class:`str`
The new static format of the asset.
Raises
------
InvalidArgument
The asset had an invalid format.
Returns
-------
:class:`Asset`
The new updated asset.
"""
if self._animated:
return self
return self.with_format(format)
class Attachment(Hashable):
"""Represents an attachment from Discord.
.. container:: operations
.. describe:: str(x)
Returns the URL of the attachment.
.. describe:: x == y
Checks if the attachment is equal to another attachment.
.. describe:: x != y
Checks if the attachment is not equal to another attachment.
.. describe:: hash(x)
Returns the hash of the attachment.
.. versionchanged:: 1.7
Attachment can now be casted to :class:`str` and is hashable.
Attributes
----------
id: :class:`int`
The attachment ID.
size: :class:`int`
The attachment size in bytes.
height: Optional[:class:`int`]
The attachment's height, in pixels. Only applicable to images and videos.
width: Optional[:class:`int`]
The attachment's width, in pixels. Only applicable to images and videos.
filename: :class:`str`
The attachment's filename.
url: :class:`str`
The attachment URL. If the message this attachment was attached
to is deleted, then this will 404.
proxy_url: :class:`str`
The proxy URL. This is a cached version of the :attr:`~Attachment.url` in the
case of images. When the message is deleted, this URL might be valid for a few
minutes or not valid at all.
content_type: Optional[:class:`str`]
The attachment's `media type <https://en.wikipedia.org/wiki/Media_type>`_
.. versionadded:: 1.7
description: Optional[:class:`str`]
The attachment's description. This is used for alternative text in the Discord client.
.. versionadded:: 2.0
"""
__slots__ = (
"id",
"size",
"height",
"width",
"filename",
"url",
"proxy_url",
"_http",
"content_type",
"description",
"_flags",
)
def __init__(self, *, data: AttachmentPayload, state: ConnectionState) -> None:
self.id: int = int(data["id"])
self.size: int = data["size"]
self.height: Optional[int] = data.get("height")
self.width: Optional[int] = data.get("width")
self.filename: str = data["filename"]
self.url: str = data.get("url")
self.proxy_url: str = data.get("proxy_url")
self._http = state.http
self.content_type: Optional[str] = data.get("content_type")
self.description: Optional[str] = data.get("description")
self._flags: int = data.get("flags", 0)
def is_spoiler(self) -> bool:
""":class:`bool`: Whether this attachment contains a spoiler."""
return self.filename.startswith("SPOILER_")
def __repr__(self) -> str:
return f"<Attachment id={self.id} filename={self.filename!r} url={self.url!r}>"
def __str__(self) -> str:
return self.url or ""
async def save(
self,
fp: Union[io.BufferedIOBase, PathLike, str],
*,
seek_begin: bool = True,
use_cached: bool = False,
) -> int:
"""|coro|
Saves this attachment into a file-like object.
Parameters
----------
fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`, :class:`str`]
The file-like object to save this attachment to or the filename
to use. If a filename is passed then a file is created with that
filename and used instead.
seek_begin: :class:`bool`
Whether to seek to the beginning of the file after saving is
successfully done.
use_cached: :class:`bool`
Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading
the attachment. This will allow attachments to be saved after deletion
more often, compared to the regular URL which is generally deleted right
after the message is deleted. Note that this can still fail to download
deleted attachments if too much time has passed and it does not work
on some types of attachments.
Raises
------
HTTPException
Saving the attachment failed.
NotFound
The attachment was deleted.
Returns
-------
:class:`int`
The number of bytes written.
"""
data = await self.read(use_cached=use_cached)
if isinstance(fp, io.BufferedIOBase):
written = fp.write(data)
if seek_begin:
fp.seek(0)
return written
with open(fp, "wb") as f: # noqa: ASYNC101
return f.write(data)
async def read(self, *, use_cached: bool = False) -> bytes:
"""|coro|
Retrieves the content of this attachment as a :class:`bytes` object.
.. versionadded:: 1.1
Parameters
----------
use_cached: :class:`bool`
Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading
the attachment. This will allow attachments to be saved after deletion
more often, compared to the regular URL which is generally deleted right
after the message is deleted. Note that this can still fail to download
deleted attachments if too much time has passed and it does not work
on some types of attachments.
Raises
------
HTTPException
Downloading the attachment failed.
Forbidden
You do not have permissions to access this attachment
NotFound
The attachment was deleted.
Returns
-------
:class:`bytes`
The contents of the attachment.
"""
url = self.proxy_url if use_cached else self.url
return await self._http.get_from_cdn(url)
async def to_file(
self,
*,
filename: Optional[str] = MISSING,
description: Optional[str] = MISSING,
use_cached: bool = False,
spoiler: bool = False,
force_close: bool = True,
) -> File:
"""|coro|
Converts the attachment into a :class:`File` suitable for sending via
:meth:`abc.Messageable.send`.
.. versionadded:: 1.3
Parameters
----------
filename: Optional[:class:`str`]
The filename to use for the file. If not specified then the filename
of the attachment is used instead.
.. versionadded:: 2.0
description: Optional[:class:`str`]
The description to use for the file. If not specified then the
description of the attachment is used instead.
.. versionadded:: 2.0
use_cached: :class:`bool`
Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading
the attachment. This will allow attachments to be saved after deletion
more often, compared to the regular URL which is generally deleted right
after the message is deleted. Note that this can still fail to download
deleted attachments if too much time has passed and it does not work
on some types of attachments.
.. versionadded:: 1.4
spoiler: :class:`bool`
Whether the file is a spoiler.
.. versionadded:: 1.4
force_close: :class:`bool`
Whether to forcibly close the bytes used to create the file
when ``.close()`` is called.
This will also make the file bytes unusable by flushing it from
memory after it is sent or used once.
Keep this enabled if you don't wish to reuse the same bytes.
.. versionadded:: 2.2
Raises
------
HTTPException
Downloading the attachment failed.
Forbidden
You do not have permissions to access this attachment
NotFound
The attachment was deleted.
Returns
-------
:class:`File`
The attachment as a file suitable for sending.
"""
data = await self.read(use_cached=use_cached)
file_filename = filename if filename is not MISSING else self.filename
file_description = description if description is not MISSING else self.description
return File(
io.BytesIO(data),
filename=file_filename,
description=file_description,
spoiler=spoiler,
force_close=force_close,
)
def to_dict(self) -> AttachmentPayload:
result: AttachmentPayload = {
"filename": self.filename,
"id": self.id,
"proxy_url": self.proxy_url,
"size": self.size,
"url": self.url,
"spoiler": self.is_spoiler(),
}
if self.height:
result["height"] = self.height
if self.width:
result["width"] = self.width
if self.content_type:
result["content_type"] = self.content_type
if self.description:
result["description"] = self.description
return result
def flags(self) -> AttachmentFlags:
"""Optional[:class:`AttachmentFlags`]: The avaliable flags that the attachment has.
.. versionadded:: 2.6
"""
return AttachmentFlags._from_value(self._flags)
def is_remix(self) -> bool:
""":class:`bool`: Whether the attachment is remixed."""
return self.flags.is_remix
async def obj_to_base64_data(obj: Optional[Union[bytes, Attachment, Asset, File]]) -> Optional[str]:
if obj is None:
return obj
if isinstance(obj, bytes):
return _bytes_to_base64_data(obj)
if isinstance(obj, File):
return _bytes_to_base64_data(obj.fp.read())
return _bytes_to_base64_data(await obj.read()) | null |
160,949 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]:
r"""A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`~nextcord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
--------
Basic usage:
.. code-block:: python3
member = nextcord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = nextcord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = nextcord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with.
"""
# global -> local
_all = all
attrget = attrgetter
# Special case the single element call
if len(attrs) == 1:
k, v = attrs.popitem()
pred = attrget(_key_fmt(k))
for elem in iterable:
if pred(elem) == v:
return elem
return None
converted = [(attrget(_key_fmt(attr)), value) for attr, value in attrs.items()]
for elem in iterable:
if _all(pred(elem) == value for pred, value in converted):
return elem
return None
def parse_ratelimit_header(request: Any, *, use_clock: bool = False) -> float:
reset_after: Optional[str] = request.headers.get("X-Ratelimit-Reset-After")
if use_clock or not reset_after:
utc = datetime.timezone.utc
now = datetime.datetime.now(utc)
reset = datetime.datetime.fromtimestamp(float(request.headers["X-Ratelimit-Reset"]), utc)
return (reset - now).total_seconds()
return float(reset_after) | null |
160,950 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
async def maybe_coroutine(
f: Callable[P, Union[T, Awaitable[T]]], *args: P.args, **kwargs: P.kwargs
) -> T:
value = f(*args, **kwargs)
if _isawaitable(value):
return await value
return value # type: ignore
# type ignored as `_isawaitable` provides `TypeGuard[Awaitable[Any]]`
# yet we need a more specific type guard | null |
160,951 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
async def async_all(
gen: Iterable[Awaitable[T]], *, check: Callable[[Awaitable[T]], bool] = _isawaitable
) -> bool:
for elem in gen:
if check(elem):
elem = await elem
if not elem:
return False
return True | null |
160,952 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
async def sane_wait_for(
futures: Iterable[Awaitable[T]], *, timeout: Optional[float]
) -> Set[asyncio.Task[T]]:
ensured = [asyncio.ensure_future(fut) for fut in futures]
done, pending = await asyncio.wait(ensured, timeout=timeout, return_when=asyncio.ALL_COMPLETED)
if len(pending) != 0:
raise asyncio.TimeoutError
return done | null |
160,953 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def get_slots(cls: Type[Any]) -> Iterator[str]:
for mro in reversed(cls.__mro__):
try:
yield from mro.__slots__ # type: ignore # handled below
except AttributeError:
continue | null |
160,954 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
T = TypeVar("T")
def compute_timedelta(dt: datetime.datetime) -> float:
if dt.tzinfo is None:
dt = dt.astimezone()
now = datetime.datetime.now(datetime.timezone.utc)
return max((dt - now).total_seconds(), 0)
The provided code snippet includes necessary dependencies for implementing the `sleep_until` function. Write a Python function `async def sleep_until(when: datetime.datetime, result: Optional[T] = None) -> Optional[T]` to solve the following problem:
|coro| Sleep until a specified time. If the time supplied is in the past this function will yield instantly. .. versionadded:: 1.3 Parameters ---------- when: :class:`datetime.datetime` The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time. result: Any If provided is returned to the caller when the coroutine completes.
Here is the function:
async def sleep_until(when: datetime.datetime, result: Optional[T] = None) -> Optional[T]:
"""|coro|
Sleep until a specified time.
If the time supplied is in the past this function will yield instantly.
.. versionadded:: 1.3
Parameters
----------
when: :class:`datetime.datetime`
The timestamp in which to sleep until. If the datetime is naive then
it is assumed to be local time.
result: Any
If provided is returned to the caller when the coroutine completes.
"""
delta = compute_timedelta(when)
return await asyncio.sleep(delta, result) | |coro| Sleep until a specified time. If the time supplied is in the past this function will yield instantly. .. versionadded:: 1.3 Parameters ---------- when: :class:`datetime.datetime` The timestamp in which to sleep until. If the datetime is naive then it is assumed to be local time. result: Any If provided is returned to the caller when the coroutine completes. |
160,955 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
The provided code snippet includes necessary dependencies for implementing the `utcnow` function. Write a Python function `def utcnow() -> datetime.datetime` to solve the following problem:
A helper function to return an aware UTC datetime representing the current time. This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware datetime, compared to the naive datetime in the standard library. .. versionadded:: 2.0 Returns ------- :class:`datetime.datetime` The current aware datetime in UTC.
Here is the function:
def utcnow() -> datetime.datetime:
"""A helper function to return an aware UTC datetime representing the current time.
This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware
datetime, compared to the naive datetime in the standard library.
.. versionadded:: 2.0
Returns
-------
:class:`datetime.datetime`
The current aware datetime in UTC.
"""
return datetime.datetime.now(datetime.timezone.utc) | A helper function to return an aware UTC datetime representing the current time. This should be preferred to :meth:`datetime.datetime.utcnow` since it is an aware datetime, compared to the naive datetime in the standard library. .. versionadded:: 2.0 Returns ------- :class:`datetime.datetime` The current aware datetime in UTC. |
160,956 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
The provided code snippet includes necessary dependencies for implementing the `valid_icon_size` function. Write a Python function `def valid_icon_size(size: int) -> bool` to solve the following problem:
Icons must be power of 2 within [16, 4096].
Here is the function:
def valid_icon_size(size: int) -> bool:
"""Icons must be power of 2 within [16, 4096]."""
return not size & (size - 1) and 4096 >= size >= 16 | Icons must be power of 2 within [16, 4096]. |
160,957 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
_IS_ASCII = re.compile(r"^[\x00-\x7f]+$")
The provided code snippet includes necessary dependencies for implementing the `string_width` function. Write a Python function `def string_width(string: str) -> int` to solve the following problem:
Returns string's width.
Here is the function:
def string_width(string: str) -> int:
"""Returns string's width."""
match = _IS_ASCII.match(string)
if match:
return match.endpos
UNICODE_WIDE_CHAR_TYPE = "WFA"
func = unicodedata.east_asian_width
return sum(2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 for char in string) | Returns string's width. |
160,958 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
class Invite(Hashable):
r"""Represents a Discord :class:`Guild` or :class:`abc.GuildChannel` invite.
Depending on the way this object was created, some of the attributes can
have a value of ``None``.
.. container:: operations
.. describe:: x == y
Checks if two invites are equal.
.. describe:: x != y
Checks if two invites are not equal.
.. describe:: hash(x)
Returns the invite hash.
.. describe:: str(x)
Returns the invite URL.
The following table illustrates what methods will obtain the attributes:
+------------------------------------+--------------------------------------------------------------+
| Attribute | Method |
+====================================+==============================================================+
| :attr:`max_age` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` |
+------------------------------------+--------------------------------------------------------------+
| :attr:`max_uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` |
+------------------------------------+--------------------------------------------------------------+
| :attr:`created_at` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` |
+------------------------------------+--------------------------------------------------------------+
| :attr:`temporary` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` |
+------------------------------------+--------------------------------------------------------------+
| :attr:`uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` |
+------------------------------------+--------------------------------------------------------------+
| :attr:`approximate_member_count` | :meth:`Client.fetch_invite` with ``with_counts`` enabled |
+------------------------------------+--------------------------------------------------------------+
| :attr:`approximate_presence_count` | :meth:`Client.fetch_invite` with ``with_counts`` enabled |
+------------------------------------+--------------------------------------------------------------+
| :attr:`expires_at` | :meth:`Client.fetch_invite` with ``with_expiration`` enabled |
+------------------------------------+--------------------------------------------------------------+
If it's not in the table above then it is available by all methods.
Attributes
----------
max_age: :class:`int`
How long before the invite expires in seconds.
A value of ``0`` indicates that it doesn't expire.
code: :class:`str`
The URL fragment used for the invite.
guild: Optional[Union[:class:`Guild`, :class:`Object`, :class:`PartialInviteGuild`]]
The guild the invite is for. Can be ``None`` if it's from a group direct message.
revoked: :class:`bool`
Indicates if the invite has been revoked.
created_at: :class:`datetime.datetime`
An aware UTC datetime object denoting the time the invite was created.
temporary: :class:`bool`
Indicates that the invite grants temporary membership.
If ``True``, members who joined via this invite will be kicked upon disconnect.
uses: :class:`int`
How many times the invite has been used.
max_uses: :class:`int`
How many times the invite can be used.
A value of ``0`` indicates that it has unlimited uses.
inviter: Optional[:class:`User`]
The user who created the invite.
approximate_member_count: Optional[:class:`int`]
The approximate number of members in the guild.
approximate_presence_count: Optional[:class:`int`]
The approximate number of members currently active in the guild.
This includes idle, dnd, online, and invisible members. Offline members are excluded.
expires_at: Optional[:class:`datetime.datetime`]
The expiration date of the invite. If the value is ``None`` when received through
:meth:`Client.fetch_invite` with ``with_expiration`` enabled, the invite will never expire.
.. versionadded:: 2.0
channel: Union[:class:`abc.GuildChannel`, :class:`Object`, :class:`PartialInviteChannel`]
The channel the invite is for.
target_type: :class:`InviteTarget`
The type of target for the voice channel invite.
.. versionadded:: 2.0
target_user: Optional[:class:`User`]
The user whose stream to display for this invite, if any.
.. versionadded:: 2.0
target_application: Optional[:class:`PartialAppInfo`]
The embedded application the invite targets, if any.
.. versionadded:: 2.0
"""
__slots__ = (
"max_age",
"code",
"guild",
"revoked",
"created_at",
"uses",
"temporary",
"max_uses",
"inviter",
"channel",
"target_user",
"target_type",
"_state",
"approximate_member_count",
"approximate_presence_count",
"target_application",
"expires_at",
)
BASE = "https://discord.gg"
def __init__(
self,
*,
state: ConnectionState,
data: InvitePayload | VanityInvitePayload,
guild: Optional[Union[PartialInviteGuild, Guild]] = None,
channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None,
) -> None:
self._state: ConnectionState = state
self.max_age: Optional[int] = data.get("max_age")
self.code: Optional[str] = data.get("code")
self.guild: Optional[InviteGuildType] = self._resolve_guild(data.get("guild"), guild)
self.revoked: Optional[bool] = data.get("revoked")
self.created_at: Optional[datetime.datetime] = parse_time(data.get("created_at"))
self.temporary: Optional[bool] = data.get("temporary")
self.uses: Optional[int] = data.get("uses")
self.max_uses: Optional[int] = data.get("max_uses")
self.approximate_presence_count: Optional[int] = data.get("approximate_presence_count")
self.approximate_member_count: Optional[int] = data.get("approximate_member_count")
expires_at = data.get("expires_at", None)
self.expires_at: Optional[datetime.datetime] = (
parse_time(expires_at) if expires_at else None
)
inviter_data = data.get("inviter")
self.inviter: Optional[User] = (
None if inviter_data is None else self._state.create_user(inviter_data)
)
self.channel: Optional[InviteChannelType] = self._resolve_channel(
data.get("channel"), channel
)
target_user_data = data.get("target_user")
self.target_user: Optional[User] = (
None if target_user_data is None else self._state.create_user(target_user_data)
)
self.target_type: InviteTarget = try_enum(InviteTarget, data.get("target_type", 0))
application = data.get("target_application")
self.target_application: Optional[PartialAppInfo] = (
PartialAppInfo(data=application, state=state) if application else None
)
def from_incomplete(cls, *, state: ConnectionState, data: InvitePayload) -> Self:
guild: Optional[Union[Guild, PartialInviteGuild]]
try:
guild_data = data["guild"]
except KeyError:
# If we're here, then this is a group DM
guild = None
else:
guild_id = int(guild_data["id"])
guild = state._get_guild(guild_id)
if guild is None:
# If it's not cached, then it has to be a partial guild
guild = PartialInviteGuild(state, guild_data, guild_id)
# As far as I know, invites always need a channel
# So this should never raise.
channel: Union[PartialInviteChannel, GuildChannel] = PartialInviteChannel(data["channel"])
if guild is not None and not isinstance(guild, PartialInviteGuild):
# Upgrade the partial data if applicable
channel = guild.get_channel(channel.id) or channel
return cls(state=state, data=data, guild=guild, channel=channel)
def from_gateway(cls, *, state: ConnectionState, data: GatewayInvitePayload) -> Self:
guild_id: Optional[int] = get_as_snowflake(data, "guild_id")
guild: Optional[Union[Guild, Object]] = state._get_guild(guild_id)
channel_id = int(data["channel_id"])
if guild is not None:
channel = guild.get_channel(channel_id) or Object(id=channel_id)
else:
guild = Object(id=guild_id) if guild_id is not None else None
channel = Object(id=channel_id)
return cls(state=state, data=data, guild=guild, channel=channel) # type: ignore
def _resolve_guild(
self,
data: Optional[InviteGuildPayload],
guild: Optional[Union[Guild, PartialInviteGuild]] = None,
) -> Optional[InviteGuildType]:
if guild is not None:
return guild
if data is None:
return None
guild_id = int(data["id"])
return PartialInviteGuild(self._state, data, guild_id)
def _resolve_channel(
self,
data: Optional[InviteChannelPayload],
channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None,
) -> Optional[InviteChannelType]:
if channel is not None:
return channel
if data is None:
return None
return PartialInviteChannel(data)
def __str__(self) -> str:
return self.url
def __repr__(self) -> str:
return (
f"<Invite code={self.code!r} guild={self.guild!r} "
f"online={self.approximate_presence_count} "
f"members={self.approximate_member_count}>"
)
def __hash__(self) -> int:
return hash(self.code)
def id(self) -> Optional[str]:
"""Optional[:class:`str`]: Returns the proper code portion of the invite.
.. note::
This may be ``None`` if it is the vanity invite the code is not set.
"""
return self.code
def url(self) -> str:
""":class:`str`: A property that retrieves the invite URL.
.. note::
This may be an empty string if it is the vanity URL and the code is not set
"""
return self.BASE + "/" + self.code if self.code else ""
async def delete(self, *, reason: Optional[str] = None) -> None:
"""|coro|
Revokes the instant invite.
You must have the :attr:`~Permissions.manage_channels` permission to do this.
Parameters
----------
reason: Optional[:class:`str`]
The reason for deleting this invite. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to revoke invites.
NotFound
The invite is invalid or expired.
HTTPException
Revoking the invite failed.
"""
if not self.code:
return
await self._state.http.delete_invite(self.code, reason=reason)
The provided code snippet includes necessary dependencies for implementing the `resolve_invite` function. Write a Python function `def resolve_invite(invite: Union[Invite, str]) -> str` to solve the following problem:
Resolves an invite from a :class:`~nextcord.Invite`, URL or code. Parameters ---------- invite: Union[:class:`~nextcord.Invite`, :class:`str`] The invite. Returns ------- :class:`str` The invite code.
Here is the function:
def resolve_invite(invite: Union[Invite, str]) -> str:
"""
Resolves an invite from a :class:`~nextcord.Invite`, URL or code.
Parameters
----------
invite: Union[:class:`~nextcord.Invite`, :class:`str`]
The invite.
Returns
-------
:class:`str`
The invite code.
"""
from .invite import Invite # circular import
if isinstance(invite, Invite):
if not invite.code:
raise NotImplementedError("Can not resolve the invite if the code is `None`")
return invite.code
rx = r"(?:https?\:\/\/)?discord(?:\.gg|(?:app)?\.com\/invite)\/(.+)"
m = re.match(rx, invite)
if m:
return m.group(1)
return invite | Resolves an invite from a :class:`~nextcord.Invite`, URL or code. Parameters ---------- invite: Union[:class:`~nextcord.Invite`, :class:`str`] The invite. Returns ------- :class:`str` The invite code. |
160,959 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
class Template:
"""Represents a Discord template.
.. versionadded:: 1.4
Attributes
----------
code: :class:`str`
The template code.
uses: :class:`int`
How many times the template has been used.
name: :class:`str`
The name of the template.
description: :class:`str`
The description of the template.
creator: :class:`User`
The creator of the template.
created_at: :class:`datetime.datetime`
An aware datetime in UTC representing when the template was created.
updated_at: :class:`datetime.datetime`
An aware datetime in UTC representing when the template was last updated.
This is referred to as "last synced" in the official Discord client.
source_guild: :class:`Guild`
The source guild.
is_dirty: Optional[:class:`bool`]
Whether the template has unsynced changes.
.. versionadded:: 2.0
"""
__slots__ = (
"code",
"uses",
"name",
"description",
"creator",
"created_at",
"updated_at",
"source_guild",
"is_dirty",
"_state",
)
def __init__(self, *, state: ConnectionState, data: TemplatePayload) -> None:
self._state = state
self._store(data)
def _store(self, data: TemplatePayload) -> None:
self.code: str = data["code"]
self.uses: int = data["usage_count"]
self.name: str = data["name"]
self.description: Optional[str] = data["description"]
self.creator: Optional[User] = self._state.create_user(data.get("creator"))
self.created_at: Optional[datetime.datetime] = parse_time(data.get("created_at"))
self.updated_at: Optional[datetime.datetime] = parse_time(data.get("updated_at"))
guild_id = int(data["source_guild_id"])
guild: Optional[Guild] = self._state._get_guild(guild_id)
self.source_guild: Guild
if guild is None:
source_serialised = data["serialized_source_guild"]
source_serialised["id"] = guild_id
state = _PartialTemplateState(state=self._state)
# Guild expects a ConnectionState, we're passing a _PartialTemplateState
self.source_guild = Guild(data=source_serialised, state=state) # type: ignore
else:
self.source_guild = guild
self.is_dirty: Optional[bool] = data.get("is_dirty", None)
def __repr__(self) -> str:
return (
f"<Template code={self.code!r} uses={self.uses} name={self.name!r}"
f" creator={self.creator!r} source_guild={self.source_guild!r} is_dirty={self.is_dirty}>"
)
async def create_guild(
self,
name: str,
region: Optional[VoiceRegion] = None,
icon: Optional[Union[bytes, Asset, Attachment, File]] = None,
) -> Guild:
"""|coro|
Creates a :class:`.Guild` using the template.
Bot accounts in more than 10 guilds are not allowed to create guilds.
.. versionchanged:: 2.1
The ``icon`` parameter now accepts :class:`File`, :class:`Attachment`, and :class:`Asset`.
Parameters
----------
name: :class:`str`
The name of the guild.
region: :class:`.VoiceRegion`
The region for the voice communication server.
Defaults to :attr:`.VoiceRegion.us_west`.
icon: Optional[Union[:class:`bytes`, :class:`Asset`, :class:`Attachment`, :class:`File`]]
The :term:`py:bytes-like object`, :class:`File`, :class:`Attachment`, or :class:`Asset`
representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected.
Raises
------
HTTPException
Guild creation failed.
InvalidArgument
Invalid icon image format given. Must be PNG or JPG.
Returns
-------
:class:`.Guild`
The guild created. This is not the same guild that is
added to cache.
"""
icon_base64 = await obj_to_base64_data(icon)
region = region or VoiceRegion.us_west
region_value = region.value
data = await self._state.http.create_from_template(
self.code, name, region_value, icon_base64
)
return Guild(data=data, state=self._state)
async def sync(self) -> Template:
"""|coro|
Sync the template to the guild's current state.
You must have the :attr:`~Permissions.manage_guild` permission in the
source guild to do this.
.. versionadded:: 1.7
.. versionchanged:: 2.0
The template is no longer edited in-place, instead it is returned.
Raises
------
HTTPException
Editing the template failed.
Forbidden
You don't have permissions to edit the template.
NotFound
This template does not exist.
Returns
-------
:class:`Template`
The newly edited template.
"""
data = await self._state.http.sync_template(self.source_guild.id, self.code)
return Template(state=self._state, data=data)
async def edit(
self,
*,
name: str = MISSING,
description: Optional[str] = MISSING,
) -> Template:
"""|coro|
Edit the template metadata.
You must have the :attr:`~Permissions.manage_guild` permission in the
source guild to do this.
.. versionadded:: 1.7
.. versionchanged:: 2.0
The template is no longer edited in-place, instead it is returned.
Parameters
----------
name: :class:`str`
The template's new name.
description: Optional[:class:`str`]
The template's new description.
Raises
------
HTTPException
Editing the template failed.
Forbidden
You don't have permissions to edit the template.
NotFound
This template does not exist.
Returns
-------
:class:`Template`
The newly edited template.
"""
payload = {}
if name is not MISSING:
payload["name"] = name
if description is not MISSING:
payload["description"] = description
data = await self._state.http.edit_template(self.source_guild.id, self.code, payload)
return Template(state=self._state, data=data)
async def delete(self) -> None:
"""|coro|
Delete the template.
You must have the :attr:`~Permissions.manage_guild` permission in the
source guild to do this.
.. versionadded:: 1.7
Raises
------
HTTPException
Editing the template failed.
Forbidden
You don't have permissions to edit the template.
NotFound
This template does not exist.
"""
await self._state.http.delete_template(self.source_guild.id, self.code)
def url(self) -> str:
""":class:`str`: The template url.
.. versionadded:: 2.0
"""
return f"https://discord.new/{self.code}"
The provided code snippet includes necessary dependencies for implementing the `resolve_template` function. Write a Python function `def resolve_template(code: Union[Template, str]) -> str` to solve the following problem:
Resolves a template code from a :class:`~nextcord.Template`, URL or code. .. versionadded:: 1.4 Parameters ---------- code: Union[:class:`~nextcord.Template`, :class:`str`] The code. Returns ------- :class:`str` The template code.
Here is the function:
def resolve_template(code: Union[Template, str]) -> str:
"""
Resolves a template code from a :class:`~nextcord.Template`, URL or code.
.. versionadded:: 1.4
Parameters
----------
code: Union[:class:`~nextcord.Template`, :class:`str`]
The code.
Returns
-------
:class:`str`
The template code.
"""
from .template import Template # circular import
if isinstance(code, Template):
return code.code
rx = r"(?:https?\:\/\/)?discord(?:\.new|(?:app)?\.com\/template)\/(.+)"
m = re.match(rx, code)
if m:
return m.group(1)
return code | Resolves a template code from a :class:`~nextcord.Template`, URL or code. .. versionadded:: 1.4 Parameters ---------- code: Union[:class:`~nextcord.Template`, :class:`str`] The code. Returns ------- :class:`str` The template code. |
160,960 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]:
r"""A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`~nextcord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
--------
Basic usage:
.. code-block:: python3
member = nextcord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = nextcord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = nextcord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with.
"""
# global -> local
_all = all
attrget = attrgetter
# Special case the single element call
if len(attrs) == 1:
k, v = attrs.popitem()
pred = attrget(_key_fmt(k))
for elem in iterable:
if pred(elem) == v:
return elem
return None
converted = [(attrget(_key_fmt(attr)), value) for attr, value in attrs.items()]
for elem in iterable:
if _all(pred(elem) == value for pred, value in converted):
return elem
return None
_URL_REGEX = r"(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])"
_MARKDOWN_STOCK_REGEX = rf"(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})"
The provided code snippet includes necessary dependencies for implementing the `remove_markdown` function. Write a Python function `def remove_markdown(text: str, *, ignore_links: bool = True) -> str` to solve the following problem:
A helper function that removes markdown characters. .. versionadded:: 1.7 .. note:: This function is not markdown aware and may remove meaning from the original text. For example, if the input contains ``10 * 5`` then it will be converted into ``10 5``. Parameters ---------- text: :class:`str` The text to remove markdown from. ignore_links: :class:`bool` Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. Defaults to ``True``. Returns ------- :class:`str` The text with the markdown special characters removed.
Here is the function:
def remove_markdown(text: str, *, ignore_links: bool = True) -> str:
"""A helper function that removes markdown characters.
.. versionadded:: 1.7
.. note::
This function is not markdown aware and may remove meaning from the original text. For example,
if the input contains ``10 * 5`` then it will be converted into ``10 5``.
Parameters
----------
text: :class:`str`
The text to remove markdown from.
ignore_links: :class:`bool`
Whether to leave links alone when removing markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. Defaults to ``True``.
Returns
-------
:class:`str`
The text with the markdown special characters removed.
"""
def replacement(match: re.Match[str]):
groupdict = match.groupdict()
return groupdict.get("url", "")
regex = _MARKDOWN_STOCK_REGEX
if ignore_links:
regex = f"(?:{_URL_REGEX}|{regex})"
return re.sub(regex, replacement, text, count=0, flags=re.MULTILINE) | A helper function that removes markdown characters. .. versionadded:: 1.7 .. note:: This function is not markdown aware and may remove meaning from the original text. For example, if the input contains ``10 * 5`` then it will be converted into ``10 5``. Parameters ---------- text: :class:`str` The text to remove markdown from. ignore_links: :class:`bool` Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. Defaults to ``True``. Returns ------- :class:`str` The text with the markdown special characters removed. |
160,961 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]:
r"""A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`~nextcord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
--------
Basic usage:
.. code-block:: python3
member = nextcord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = nextcord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = nextcord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with.
"""
# global -> local
_all = all
attrget = attrgetter
# Special case the single element call
if len(attrs) == 1:
k, v = attrs.popitem()
pred = attrget(_key_fmt(k))
for elem in iterable:
if pred(elem) == v:
return elem
return None
converted = [(attrget(_key_fmt(attr)), value) for attr, value in attrs.items()]
for elem in iterable:
if _all(pred(elem) == value for pred, value in converted):
return elem
return None
_MARKDOWN_ESCAPE_REGEX = re.compile(
rf"(?P<markdown>{_MARKDOWN_ESCAPE_SUBREGEX}|{_MARKDOWN_ESCAPE_COMMON})",
re.MULTILINE,
)
_URL_REGEX = r"(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])"
_MARKDOWN_STOCK_REGEX = rf"(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})"
The provided code snippet includes necessary dependencies for implementing the `escape_markdown` function. Write a Python function `def escape_markdown(text: str, *, as_needed: bool = False, ignore_links: bool = True) -> str` to solve the following problem:
r"""A helper function that escapes Discord's markdown. Parameters ---------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns ------- :class:`str` The text with the markdown special characters escaped with a slash.
Here is the function:
def escape_markdown(text: str, *, as_needed: bool = False, ignore_links: bool = True) -> str:
r"""A helper function that escapes Discord's markdown.
Parameters
----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns
-------
:class:`str`
The text with the markdown special characters escaped with a slash.
"""
if not as_needed:
def replacement(match: re.Match[str]):
groupdict = match.groupdict()
is_url = groupdict.get("url")
if is_url:
return is_url
return "\\" + groupdict["markdown"]
regex = _MARKDOWN_STOCK_REGEX
if ignore_links:
regex = f"(?:{_URL_REGEX}|{regex})"
return re.sub(regex, replacement, text, count=0, flags=re.MULTILINE)
text = re.sub(r"\\", r"\\\\", text)
return _MARKDOWN_ESCAPE_REGEX.sub(r"\\\1", text) | r"""A helper function that escapes Discord's markdown. Parameters ---------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns ------- :class:`str` The text with the markdown special characters escaped with a slash. |
160,962 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
The provided code snippet includes necessary dependencies for implementing the `escape_mentions` function. Write a Python function `def escape_mentions(text: str) -> str` to solve the following problem:
A helper function that escapes everyone, here, role, and user mentions. .. note:: This does not include channel mentions. .. note:: For more granular control over what mentions should be escaped within messages, refer to the :class:`~nextcord.AllowedMentions` class. Parameters ---------- text: :class:`str` The text to escape mentions from. Returns ------- :class:`str` The text with the mentions removed.
Here is the function:
def escape_mentions(text: str) -> str:
"""A helper function that escapes everyone, here, role, and user mentions.
.. note::
This does not include channel mentions.
.. note::
For more granular control over what mentions should be escaped
within messages, refer to the :class:`~nextcord.AllowedMentions`
class.
Parameters
----------
text: :class:`str`
The text to escape mentions from.
Returns
-------
:class:`str`
The text with the mentions removed.
"""
return re.sub(r"@(everyone|here|[!&]?[0-9]{17,20})", "@\u200b\\1", text) | A helper function that escapes everyone, here, role, and user mentions. .. note:: This does not include channel mentions. .. note:: For more granular control over what mentions should be escaped within messages, refer to the :class:`~nextcord.AllowedMentions` class. Parameters ---------- text: :class:`str` The text to escape mentions from. Returns ------- :class:`str` The text with the mentions removed. |
160,963 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
The provided code snippet includes necessary dependencies for implementing the `parse_raw_mentions` function. Write a Python function `def parse_raw_mentions(text: str) -> List[int]` to solve the following problem:
A helper function that parses mentions from a string as an array of :class:`~nextcord.User` IDs matched with the syntax of ``<@user_id>`` or ``<@!user_id>``. .. note:: This does not include role or channel mentions. See :func:`parse_raw_role_mentions` and :func:`parse_raw_channel_mentions` for those. .. versionadded:: 2.2 Parameters ---------- text: :class:`str` The text to parse mentions from. Returns ------- List[:class:`int`] A list of user IDs that were mentioned.
Here is the function:
def parse_raw_mentions(text: str) -> List[int]:
"""A helper function that parses mentions from a string as an array of :class:`~nextcord.User` IDs
matched with the syntax of ``<@user_id>`` or ``<@!user_id>``.
.. note::
This does not include role or channel mentions. See :func:`parse_raw_role_mentions`
and :func:`parse_raw_channel_mentions` for those.
.. versionadded:: 2.2
Parameters
----------
text: :class:`str`
The text to parse mentions from.
Returns
-------
List[:class:`int`]
A list of user IDs that were mentioned.
"""
return [int(x) for x in re.findall(r"<@!?(\d{15,20})>", text)] | A helper function that parses mentions from a string as an array of :class:`~nextcord.User` IDs matched with the syntax of ``<@user_id>`` or ``<@!user_id>``. .. note:: This does not include role or channel mentions. See :func:`parse_raw_role_mentions` and :func:`parse_raw_channel_mentions` for those. .. versionadded:: 2.2 Parameters ---------- text: :class:`str` The text to parse mentions from. Returns ------- List[:class:`int`] A list of user IDs that were mentioned. |
160,964 | from __future__ import annotations
import array
import asyncio
import datetime
import functools
import inspect
import json
import re
import sys
import unicodedata
import warnings
from base64 import b64encode
from bisect import bisect_left
from inspect import isawaitable as _isawaitable, signature as _signature
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
ForwardRef,
Generic,
Iterable,
Iterator,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from .errors import InvalidArgument
from .file import File
The provided code snippet includes necessary dependencies for implementing the `parse_raw_role_mentions` function. Write a Python function `def parse_raw_role_mentions(text: str) -> List[int]` to solve the following problem:
A helper function that parses mentions from a string as an array of :class:`~nextcord.Role` IDs matched with the syntax of ``<@&role_id>``. .. versionadded:: 2.2 Parameters ---------- text: :class:`str` The text to parse mentions from. Returns ------- List[:class:`int`] A list of role IDs that were mentioned.
Here is the function:
def parse_raw_role_mentions(text: str) -> List[int]:
"""A helper function that parses mentions from a string as an array of :class:`~nextcord.Role` IDs
matched with the syntax of ``<@&role_id>``.
.. versionadded:: 2.2
Parameters
----------
text: :class:`str`
The text to parse mentions from.
Returns
-------
List[:class:`int`]
A list of role IDs that were mentioned.
"""
return [int(x) for x in re.findall(r"<@&(\d{15,20})>", text)] | A helper function that parses mentions from a string as an array of :class:`~nextcord.Role` IDs matched with the syntax of ``<@&role_id>``. .. versionadded:: 2.2 Parameters ---------- text: :class:`str` The text to parse mentions from. Returns ------- List[:class:`int`] A list of role IDs that were mentioned. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.