Migrer vers la version 2.0¶
La version 2.0 a introduit de nouvelles fonctionnalités Discord et a marqué certaines anciennes fonctionnalités comme obsolètes.
Une partie de la refonte implique la création de commandes d’application et de composants. Ces changements incluent une nouvelle classe Bot, ui.View, et une nouvelle classe ApplicationContext. Si vous êtes intéressé par leur création, veuillez consulter notre guide.
Changement de version de Python¶
Afin de faciliter le développement et de permettre à nos dépendances de se mettre à jour pour supporter Python 3.8 ou une version supérieure, la bibliothèque a dû retirer le support des versions de Python inférieures à 3.7, ce qui signifie essentiellement que le support pour Python 3.7 et les versions antérieures a été abandonné.
Changements majeurs des modèles¶
Ci-dessous sont les changements majeurs qui se sont produits dans la v2.0 :
Suppression du support des comptes utilisateurs¶
Avant la version 2.0, les comptes utilisateurs étaient pris en charge. Cela allait à l’encontre de l’esprit de la bibliothèque et des conditions d’utilisation de Discord, et a été supprimé. Ainsi, les fonctionnalités qui leur étaient exclusivement réservées ont été supprimées :
L’argument
botdeClient.start()etClient.run()L’argument
afkdeClient.change_presence()Classes
Profile,Relationship,Call Message,Group CallRelationshipType,HypeSquadHouse,PremiumType,UserContentFilter,FriendFlags,ThemeGroupChannel.add_recipients,remove_recipients,edit(NOTE :GroupChannellui-même reste toujours)Guild.ackClient.self_botClient.fetch_user_profileMessage.calletackClientUser.email,premium,premium_type,get_relationship,relationships,friends,blocked,create_group,edit_settingsArguments de
ClientUser.edit:password,new_password,email,houseUser.relationship,mutual_friends,is_friend,is_blocked,block,Unblock,remove_friend,send_friend_request,profileÉvénements :
on_relationship_addeton_relationship_update
Temps conscient du fuseau horaire¶
utcnow devient now(datetime.timezone.utc). Si vous construisez vous-même un objet datetime.datetime, passez tzinfo=datetime.timezone.utc.
embed = discord.Embed(
title = "Pi Day 2021 in UTC",
timestamp = datetime(2021, 3, 14, 15, 9, 2, tzinfo=timezone.utc)
)
Note that newly-added utils.utcnow() can be used as an alias of datetime.datetime.now(datetime.timezone.utc).
Asset Changes¶
Les attributs liés aux actifs qui renvoyaient auparavant des chaînes de hachage (par exemple User.avatar) renvoient maintenant Asset. Asset.key renvoie le hachage à partir de maintenant.
Les méthodes
Asset.replace()ouAsset.with_x()peuvent être utilisées pour obtenir des tailles ou des types d’actifs spécifiques.Emoji.urletPartialEmoji.urlsont maintenantstr.Emoji.save()etEmoji.read()sont ajoutés pour sauvegarder ou lire les emojis.Emoji.url_asetPartialEmoji.url_asont été supprimés.Certains attributs
AuditLogDiffrenvoient maintenantAssetau lieu destr, :AuditLogDiff.splash,AuditLogDiff.icon,AuditLogDiff.avatarUser.avatarrenvoie None` si l’avatar n’est pas défini et est à la place l’avatar par défaut ; utilisezUser.display_avatarpour un comportement similaire à celui précédant la version 2.0.
Avant |
Après |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Webhook Changes¶
class:Webhook et
WebhookMessagesont maintenant toujours asynchrones. Pour une utilisation synchrone (requests), utilisezSyncWebhooketSyncWebhookMessage.WebhookAdapter, AsyncWebhookAdapter, et RequestsWebhookAdapter sont supprimés, car ils sont inutiles.
adapterarguments ofWebhook.partial()andWebhook.from_url()are removed. Sessions are now passed directly topartial/from_url.
webhook = discord.SyncWebhook.from_url(
f"https://discord.com/api/webhooks/{id}/{token}"
)
webhook.send("Hello from Pycord 2.0")
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.partial(
id,
token,
session=session
)
await webhook.send("Hello from Pycord 2.0")
Intents Changes¶
Intents.message_content is now a privileged intent. Disabling it causes Message.content,
Message.embeds, Message.components, and Message.attachments to be empty (an empty string
or an empty array), directly causing ext.commands.Command s to not run.
See here for more information.
Threads Introduced¶
The following methods and attributes can return Thread objects:
Permission Changes¶
permissions_in has been removed in favor of checking the permissions of the channel for said user.
Avant |
Après |
|
|
|
|
Edit Method Behavior Change¶
edit methods of most classes no longer update the cache in-place, and instead returns the modified object.
Positional-Keyword Argument Split¶
The following are now positional only:
The following are now keyword only:
Event Changes¶
on_presence_update()replaces on_member_update for updates toMember.statusandMember.activities.on_private_channel_create/deletewill no longer be dispatched due to Discord changes.on_socket_raw_receive()is no longer dispatched for incomplete data, and the value passed is always decompressed and decoded tostr. Previously, when received a multi-part zlib-compressed binary message,on_socket_raw_receive()was dispatched on all messages with the compressed, encodedbytes.
Message.type For Replies¶
Message.type now returns MessageType.reply for replies, instead of MessageType.default.
Sticker Changes¶
Sticker.preview_imagewas removed as Discord no longer provides the data.StickerType, an enum of sticker formats, is renamed toStickerFormatType. Old name is used for a new enum with different purpose (checking if the sticker is guild sticker or Nitro sticker).Message.stickersis now List[StickerItem] instead of List[Sticker]. WhileStickerItemsupports some operations of previousSticker,descriptionandpack_idattributes do not exist.Stickercan be fetched viaStickerItem.fetch()method.Sticker.imageis removed.Stickercan still be fetched viaSticker.read()orSticker.save()and its URL can be accessed viaSticker.url, just like newEmoji.Due to the introduction of
GuildSticker,Sticker.tagsis removed from the parent classStickerand moved toStandardSticker.tags.
Type Changes¶
Many method arguments now reject None or return None.
DMChannel.recipientis now optional, and will returnNonein many cases.User.avatarreturnsNoneif the avatar is not set and is instead the default avatar.Guild.create_text_channel’stopicargument no longer acceptsNone.Guild.vanity_invitecan now returnNone.Template.edit’snameargument no longer acceptsNone.Member.edit’srolesargument no longer acceptsNone.Bot.add_listenerandBot.remove_listener’snamearguments no longer acceptNone.The following
ext.commands.Contextattributes can now beNone:prefix,command,invoked_with,invoked_subcommand.ext.commands.Command.helpcan now beNone.
Miscellaneous Changes¶
The following were removed:
Client.request_offline_membersClient.logoutExtensionNotFound.originalMemberCacheFlags.onlineguild_subscriptionsargument ofClientfetch_offline_membersargument ofClientHelpCommand.clean_prefixmoved toext.commands.Context.clean_prefixVerificationLevel.table_flip(alias ofhigh) was removed.extreme,very_high, anddouble_table_flipattributes were removed and replaced withVerificationLevel.highest.
The following were renamed:
Colour.blurpleis renamed toColour.og_blurple, andColour.blurplenow returns the newer color.missing_permsarguments and attributes ofext.commands.MissingPermissionsandext.commands.BotMissingPermissionsare renamed tomissing_permissions.
The following were changed in behavior:
Embedthat has a value is always considered truthy. Previously it only considered text fields.Bot.add_cog()now raises an error when a cog with the same name is already registered.overrideargument can be used to bring back the 1.x behavior.StageChannel.edit()can no longer edittopic. UseStageInstance.edit()instead.StageChannel.clone()no longer clones its topic.
The following were changed in types:
ext.commands.Command.clean_paramsis now adict, notOrderedDict.Reaction.custom_emojiis nowReaction.is_custom_emojifor consistency.IntegrationAccount.idis nowstr, instead ofint, due to Discord changes.AuditLogDiff.typeis now Union[ChannelType,StickerType], instead ofChannelType.
Parting Words¶
The v2.0 of the library implemented a lot of new features. To implement newer features, such as slash commands, they can be seen on our guide.