As someone commented earlier, chemicals such as nicotine and morphine were products of evolution meant to repel animals. It is explained in more details in this article here.
Evolutionary biologists studying plant–herbivore interactions have convincingly argued that many plant secondary metabolites, including alkaloids such as nicotine, morphine and cocaine, are potent neurotoxins that evolved to deter consumption by herbivores.
But it seems that those same chemicals produce adverse effects to what they were originally intended for:
For example, one or more plant alkaloids have been identified that interfere with nearly every step in neural signalling. Targets include neurotransmitter synthesis, storage, release, binding, deactivation and reuptake, ion channel activation and function, and key enzymes involved in signal transduction.
Paradoxically, the same properties invoked to explain why common drugs like caffeine, nicotine and cocaine are toxic are also those invoked to explain why these compounds are rewarding. It is therefore important to stress that these and other addictive drugs appear to have evolved only because they successfully deterred, not rewarded or reinforced, plant consumption.
For example, let's take a closer look at nicotine. This compound is not present at all times in the plant, instead it is produced as a reaction to a trigger.
Nicotiana attenuata is an important model species for the analysis of plant–herbivore interactions involving nicotine. It is a domesticated North American tobacco plant that is attacked by over 20 different herbivores, ranging from mammalian browsers to intracellular-feeding insects. These attacks elicit a battery of defensive responses, including nicotine production.
Nicotiana has therefore evolved to allocate chemical defences strategically by concentrating them in the most valuable parts of the plant, such as young leaves, stems and reproductive organs, and by modulating its production according to the type of herbivore and extent of leaf damage.
This last example concentrates on nicotine, but it makes it easier to grasp how plants might use the production of such a chemical as a mean of protection.
Also, depending on the substance and the creature which consumes the plant, one might witness different outcomes. I found interesting information in this less detailed text here:
Defensive compounds from plants, like nicotine and cocaine, usually target nervous system components in insects. These components include proteins that have important roles on the insect’s physiology, which may include specific receptors, ion channels, enzymes, etc. In most cases, the defensive chemical kills the insect by interfering with one or more of these proteins; in other cases, the chemicals just make the plant distasteful for the insect, and therefore, the bug will leave the plant alone.